温馨提示×

c语言怎么用sizeof求字符串长度

小亿
162
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