c语言输入句子统计单词
时间: 2023-11-15 10:48:58 浏览: 65
以下是一个简单的C语言程序,可以实现输入句子并统计单词的功能:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char sentence[100];
int word_count = 0;
printf("请输入一个句子:");
fgets(sentence, 100, stdin);
// 使用 strtok 函数分割句子,统计单词数
char *word = strtok(sentence, " ");
while (word != NULL) {
word_count++;
word = strtok(NULL, " ");
}
printf("该句子中共有 %d 个单词。\n", word_count);
return 0;
}
```
该程序使用了标准库函数 `fgets` 和 `strtok`,前者用于从标准输入中读入句子,后者则用于分割句子并统计单词数。具体而言,`strtok` 函数的第一个参数为需要分割的字符串,第二个参数为分割符,返回值为分割出的第一个单词的指针。每次调用 `strtok` 函数时,它会自动从上一次结束的位置开始继续分割,直到整个字符串都被分割完为止。
相关问题
c语言输入一个句子统计单词个数
当然可以。您可以使用以下代码来完成这个任务:
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char sentence[1000];
int word_count = 0, i;
printf("请输入句子:\n");
fgets(sentence, sizeof(sentence), stdin);
// 判断单词数
for (i = 0; sentence[i] != '\0'; i++) {
if (isspace(sentence[i]) || sentence[i] == '\n') {
word_count++;
}
}
printf("该句子中有 %d 个单词。\n", word_count);
return 0;
}
```
这个程序会提示用户输入一个句子,然后将句子存储到数组中。之后,它将遍历数组,当遇到空格或换行符时,将单词计数增加1。最后,程序将输出单词数。
注意:程序假设用户输入的句子不会超过1000个字符。如果您需要处理更长的句子,您需要相应地调整数组大小。
c语言统计英文句子单词个数
可以使用C语言的字符串处理函数和循环语句来统计英文句子中的单词个数。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char sentence[1000];
int wordCount = 0;
printf("请输入一个英文句子:\n");
fgets(sentence, sizeof(sentence), stdin); // 从标准输入读取一行字符串
char* token = strtok(sentence, " "); // 使用空格作为分隔符,获取第一个单词
while (token != NULL) {
wordCount++; // 统计单词个数
token = strtok(NULL, " "); // 继续获取下一个单词
}
printf("单词个数为:%d\n", wordCount);
return 0;
}
```
该程序首先使用 `fgets` 函数从标准输入读取一个英文句子,并将其存储在字符数组 `sentence` 中。然后使用 `strtok` 函数将句子按照空格分隔为多个单词,使用循环语句统计单词个数。最后输出单词个数。