c语言字符串个数如何统计
在C语言中,可以通过以下方法统计字符串的个数:
- 使用循环遍历字符串,统计字符串中的非空字符个数;
- 使用标准库函数strlen()获取字符串的长度,即字符个数;
- 使用标准库函数strtok()分割字符串,统计分割得到的子字符串个数。
下面是使用循环遍历字符串的示例代码:
#include <stdio.h>
int countStrings(char* str) {
int count = 0;
int i = 0;
while (str[i] != '\0') {
if (str[i] != ' ')
count++;
i++;
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
int count = countStrings(str);
printf("字符串个数:%d\n", count);
return 0;
}
在上面的示例代码中,通过循环遍历字符串,统计字符串中非空字符的个数。空格字符不包括在统计中。