用C语言实现程序,输入一行字符(可能包含英文字母,数字字符等其它字符),要求统计其中单词的个数,单词只由英文字母构成
时间: 2024-05-08 22:22:11 浏览: 8
可以通过遍历输入的字符数组,根据单词的定义来统计单词个数。
以下是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int countWords(char *str) {
int count = 0;
int is_word = 0; // 标记是否在单词中
while (*str != '\0') {
// 如果当前字符是英文字母,则标记为在单词中
if (isalpha(*str)) {
is_word = 1;
}
// 如果当前字符不是英文字母,且之前在单词中,则单词数+1
else if (is_word) {
count++;
is_word = 0;
}
str++;
}
// 如果最后一个字符是英文字母,则需要额外计数
if (is_word) {
count++;
}
return count;
}
int main() {
char str[100];
printf("请输入一行字符:");
fgets(str, 100, stdin);
int count = countWords(str);
printf("单词个数为:%d\n", count);
return 0;
}
```
在上面的代码中,`countWords` 函数接收一个字符数组指针 `str`,遍历该数组,通过标记 `is_word` 来判断是否在单词中,从而统计单词个数。`main` 函数中使用 `fgets` 函数读取输入的字符串,并调用 `countWords` 函数来统计单词个数。