统计两行英文中单词个数
时间: 2024-06-15 10:08:07 浏览: 10
要统计两行英文中的单词个数,可以按照以下步骤进行:
1. 首先,将两行英文分别存储在两个字符串变量中。
2. 定义一个计数器变量,用于记录单词的个数。
3. 使用循环遍历每个字符,判断是否为字母或者数字。如果是,则表示一个单词的开始;如果不是,则表示一个单词的结束。
4. 在判断到单词的开始时,将计数器加1。
5. 最后,输出计数器的值,即为两行英文中的单词个数。
下面是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int countWords(char *str) {
int count = 0;
int isWord = 0;
while (*str) {
if (isalnum(*str)) {
if (!isWord) {
count++;
isWord = 1;
}
} else {
isWord = 0;
}
str++;
}
return count;
}
int main() {
char line1[100];
char line2[100];
printf("请输入第一行英文:");
fgets(line1, sizeof(line1), stdin);
printf("请输入第二行英文:");
fgets(line2, sizeof(line2), stdin);
int count1 = countWords(line1);
int count2 = countWords(line2);
printf("第一行英文中的单词个数:%d\n", count1);
printf("第二行英文中的单词个数:%d\n", count2);
return 0;
}
```
请注意,上述代码中使用了`countWords`函数来统计单词个数,该函数接受一个字符串参数,并返回该字符串中的单词个数。在`main`函数中,我们分别输入两行英文,并调用`countWords`函数来统计单词个数,并输出结果。