c语言统计数组中单词个数
时间: 2023-10-30 15:05:05 浏览: 48
假设单词之间以空格分隔,可以通过遍历数组元素并计数空格数来统计单词个数。以下是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int countWords(char arr[], int len) {
int wordCount = 0;
int i;
for (i = 0; i < len; i++) {
if (isspace(arr[i])) { // 空格表示一个单词结束
wordCount++;
}
}
// 最后一个单词后面没有空格,需要额外计数
wordCount++;
return wordCount;
}
int main() {
char arr[] = "hello world, how are you?";
int len = sizeof(arr) / sizeof(char); // 计算数组长度
int wordCount = countWords(arr, len);
printf("单词个数为 %d\n", wordCount);
return 0;
}
```
输出:
```
单词个数为 5
```
相关问题
c语言统计字符数组中单词个数
以下是一个C语言统计字符数组中单词个数的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello Everyone";
int i, word, flag;
word = 0;
flag = 0;
for (i = 0; str[i] != '\0';++) {
if (str[i] ==' ') {
flag = 0;
} else if (flag == 0) {
word++;
flag = 1;
}
}
printf("word=%d\n", word);
}
```
输出结果为:
```
word=2
```
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` 函数将句子按照空格分隔为多个单词,使用循环语句统计单词个数。最后输出单词个数。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)