How do you output the length of a string in C language?

In C language, the length of a string can be obtained using the strlen function. This function is defined in the string.h header file.

Here is a simple example:

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

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

    printf("字符串的长度是:%d\n", length);

    return 0;
}

The output result:

字符串的长度是:13

In the example above, we use the strlen function to obtain the length of the string “Hello, World!” and assign the result to the variable length. We then use the printf function to output the length of the string to the console.

bannerAds