How to calculate the length of a C string?
In C language, the standard library function strlen() can be used to calculate the length of a string. The strlen() function is located in the string.h header file.
The following is an example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
printf("字符串的长度为:%d\n", len);
return 0;
}
The output result is:
字符串的长度为:13
In the above example, a char array named str is defined and initialized to “Hello, world!”. The strlen() function is then used to calculate the length of the string, and the result is assigned to the variable len. Finally, the length of the string is output using the printf() function.