C String Length: strlen() Function Guide
In C language, you can use the strlen() function to obtain the length of a string. This function is defined in the
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("输入一个字符串:");
fgets(str, 100, stdin); // 从标准输入读取字符串
str[strcspn(str, "\n")] = 0; // 去除fgets()函数读取的换行符
int len = strlen(str);
printf("字符串的长度为:%d\n", len);
return 0;
}
In the example above, we used the fgets() function to read a string from standard input, removed the newline character with the strcspn() function. We then used the strlen() function to get the length of the string and print the result.