How to calculate the length of a string using the sizeof operator in the C language?

In C language, you can use the strlen function to calculate the length of a string. The sizeof operator is used to calculate the number of bytes occupied by a variable or data type.

Here is the sample code:

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

int main() {
    char str[100] = "Hello, World!";
    int len = strlen(str);
    printf("字符串的长度是:%d\n", len);
    printf("字符串所占的字节数是:%lu\n", sizeof(str));
    
    return 0;
}

The output is:

字符串的长度是:13
字符串所占的字节数是:100

The strlen function returns the length of a string, which is the number of characters in the string (excluding the null character ‘\0’), while the sizeof operator returns the total number of bytes occupied by the string variable.

bannerAds