在C语言中统计字符串中单词的个数,通常采用遍历字符串并利用标志位判断单词边界的方法。以下是具体实现步骤及示例代码:
一、核心思路
初始化变量
- `count`:记录单词个数,初始值为0。 - `flag`:标志位,用于判断当前是否处于单词内部,初始值为0。
遍历字符串
- 从左到右逐个字符检查:
- 若遇到空格且`flag`为0,表示单词结束,`count`加1;
- 若遇到非空格且`flag`为0,表示新单词开始,`count`加1并设置`flag`为1。
处理特殊情况
- 字符串开头或结尾的空格不统计;
- 连续多个空格视为单个分隔符。
二、示例代码
方法一:使用标志位判断单词边界
```c
include include include int count_words(const char *str) { int count = 0, flag = 0; for (int i = 0; str[i] != '\0'; i++) { if (isspace(str[i])) { flag = 0; } else if (!flag) { count++; flag = 1; } } return count; } int main() { char str; printf("请输入字符串:\n"); fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; // 去除换行符 printf("单词数:%d\n", count_words(str)); return 0; } ``` 方法二:统计连续空格并优化 ```c include include include int count_words(const char *str) { int count = 0, consecutive_spaces = 0; for (int i = 0; str[i] != '\0'; i++) { if (isspace(str[i])) { consecutive_spaces++; } else { if (consecutive_spaces > 0) { count++; consecutive_spaces = 0; } } } return count; } int main() { char str; printf("请输入字符串:\n"); fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; // 去除换行符 printf("单词数:%d\n", count_words(str)); return 0; } ``` 三、注意事项 使用`fgets`读取输入时,需去除末尾的换行符(`strcspn(str, "\n")`); 若字符串仅包含空格,结果应为0; 处理标点符号时,可根据需求调整条件(如仅统计字母数字开头的单词)。