溫馨提示×

C語言中怎么用sizeof求字符串長度

小億
971
2023-12-07 12:23:32
欄目: 編程語言

在C語言中,可以使用sizeof運算符來求字符串的長度。但是需要注意的是,sizeof運算符求得的是字符串在內存中占用的字節數,而不是字符串的實際長度(即字符的個數)。

如果想要求字符串的實際長度,可以使用strlen函數。下面是使用sizeof和strlen兩種方法求字符串長度的示例代碼:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!";
    int size_with_sizeof = sizeof(str);
    int size_with_strlen = strlen(str);

    printf("Size of str (with sizeof): %d\n", size_with_sizeof);
    printf("Size of str (with strlen): %d\n", size_with_strlen);

    return 0;
}

輸出結果為:

Size of str (with sizeof): 15
Size of str (with strlen): 13

可以看到,使用sizeof求得的字符串長度為15,而使用strlen求得的字符串長度為13,因為strlen函數會計算字符串中的有效字符個數,不包括字符串結尾的空字符’\0’。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女