c语言统计单词个数
时间: 2023-07-02 12:04:13 浏览: 31
以下是一个简单的 C 语言程序,可以统计输入文本中的单词数量。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
int count = 0;
char c, prev = ' ';
printf("Enter text: ");
while ((c = getchar()) != '\n') {
if (isspace(c) && !isspace(prev)) {
count++;
}
prev = c;
}
if (!isspace(prev)) {
count++;
}
printf("Word count: %d\n", count);
return 0;
}
```
该程序从标准输入读取一行文本,并使用 isspace() 函数检查字符是否为空格、制表符或换行符。如果当前字符为空格等空白字符,并且上一个字符不是空白字符,则将单词计数器加 1。最后,如果最后一个字符不是空白字符,则再将单词计数器加 1。
相关问题
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` 函数将句子按照空格分隔为多个单词,使用循环语句统计单词个数。最后输出单词个数。
c语言统计文件中单词个数
你可以使用C语言中的文件操作函数,例如fopen、fread、fclose等,以及字符串操作函数,如strtok、strcmp和strlen等来实现统计文件中单词个数的功能。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_WORD_LENGTH 50
int main() {
char filename[100];
printf("请输入文件名:");
scanf("%s", filename);
FILE *fp;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("文件打开失败!\n");
return 1;
}
char line[1000], word[MAX_WORD_LENGTH];
int count = 0;
while (fgets(line, 1000, fp) != NULL) {
char *token = strtok(line, " \t\n\r"); // 按空格、制表符、换行符分割单词
while (token != NULL) {
strcpy(word, token);
if (strlen(word) > 0) {
count++;
}
token = strtok(NULL, " \t\n\r");
}
}
printf("单词个数为:%d\n", count);
fclose(fp);
return 0;
}
```
该程序首先要求用户输入文件名,然后打开文件并逐行读取文件,使用strtok函数将每行文本按照空格、制表符、换行符等分割为单词,然后判断单词长度是否大于0,如果是则累加单词个数。最后输出单词个数并关闭文件。