C語言判斷字符串長度的方法小結
strlen()
在C語言中,可以使用strlen()函數來計算一個字符串的長度(不包括字符串末尾的空字符’\0’)。例如:
在使用strlen函數時,需要添加string.h頭文件。
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello c";
int length = strlen(str);
printf("字符串長度為%d\n",length);
return 0;
}
上面的代碼段將輸出:字符串長度為7,因為字符串"hello c"包含7個字符。
自定義函數
如果不想使用sizeof()和strlen(),可以利用循環(huán)來判斷字符串的長度。
編寫函數通過傳入一個字符串,返回一個長度數值。
#include <stdio.h>
#include <string.h>
int func_length(char str[]){
char *p = str;
int cnt = 0;
while(*p!='\0'){
cnt++; // 計數
p++;
}
return cnt;
}
int main() {
char str[] = "hello c";
int length = func_length(str);
printf("字符串長度為%d\n",length);
return 0;
}
輸出結果:字符串長度為7
區(qū)別:sizeof()
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello c";
printf("字符串長度為%d\n",sizeof(str));
return 0;
}
輸出結果:字符串長度為8
注意:在C語言中,sizeof() 是長度的運算符,括號中可以放入數據類型或者表達式,一般我們用來計算字符串長度。
在使用sizeof()求字符串長度時,會將 ‘\0’ 也計算到字符串長度中。例如"abcd"用sizeof()求長度會計算得到5。
char str[100]=“”; sizeof(str)的值是100。
到此這篇關于C語言判斷字符串長度的方法小結的文章就介紹到這了,更多相關C語言判斷字符串長度內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C/C++?Qt?StringListModel?字符串列表映射組件詳解
StringListModel?字符串列表映射組件,該組件用于處理字符串與列表框組件中數據的轉換,通常該組件會配合ListView組件一起使用,本文給大家介紹了C/C++?Qt?StringListModel?字符串列表映射組件的相關知識,感興趣的朋友跟隨小編一起看看吧2021-12-12
Visual?Studio?2019?Qt?QML?項目環(huán)境搭建常見問題處理
本文主要介紹了Visual?Studio?2019?Qt?QML?項目環(huán)境搭建常見問題處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-03-03

