溫馨提示×

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

小億
372
2023-11-16 13:10:42
欄目: 編程語言

在C語言中,可以使用sizeof操作符來獲取字符串的長度。但需要注意的是,sizeof操作符獲取的是字符串變量的字節大小,而不是字符串的實際長度。

為了獲取字符串的實際長度,可以使用strlen函數。strlen函數會遍歷字符串中的字符直到遇到字符串結束符\0,然后返回遍歷過的字符數(不包括結束符)。

以下是使用sizeofstrlen來求字符串長度的示例:

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

int main() {
    char str[] = "Hello";
    int length1 = sizeof(str) - 1;  // 使用sizeof
    int length2 = strlen(str);     // 使用strlen

    printf("Length 1: %d\n", length1);
    printf("Length 2: %d\n", length2);

    return 0;
}

輸出結果:

Length 1: 5
Length 2: 5

在上面的示例中,sizeof(str)會返回str數組所占的字節大小,因此需要減去1來得到字符串的實際長度。而strlen(str)會返回字符串的實際長度,不包括結束符。

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