c语言 统计一个字符串中的英文单词个数
时间: 2024-06-13 11:07:13 浏览: 5
以下是C语言统计一个字符串中的英文单词个数的代码示例:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, word_count = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 如果当前字符是字母
while (isalpha(str[i])) { // 继续往后找字母
i++;
}
word_count++; // 找到一个单词
}
}
printf("该字符串中的英文单词个数为:%d\n", word_count);
return 0;
}
```
该程序首先提示用户输入一个字符串,然后使用`fgets()`函数读取用户输入的字符串。接着,程序遍历整个字符串,如果当前字符是字母,则继续往后找字母,直到找到一个非字母字符,此时就找到了一个单词,单词计数器加1。最后,程序输出该字符串中的英文单词个数。
相关问题
通过C语言统计字符串中的单词个数
可以使用C语言的字符串处理函数和循环语句来统计字符串中的单词个数。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int countWords(char str[]) {
int i, count = 0, word = 0;
for (i = 0; i < strlen(str); i++) {
if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') {
word = 0;
} else if (word == 0) {
word = 1;
count++;
}
}
return count;
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Number of words: %d", countWords(str));
return 0;
}
```
在上面的例子中,`countWords`函数使用循环遍历字符串中的每个字符。如果当前字符是空格、换行符或制表符,则将`word`变量设置为0,表示当前不在单词中。如果当前字符不是空格、换行符或制表符,且`word`变量为0,则将`word`变量设置为1,并将`count`计数器加1,表示当前在单词中。最后返回`count`计数器的值,即为字符串中的单词个数。
c语言统计字符串中单词个数
可以使用以下方法来统计字符串中单词的个数:
1. 遍历字符串中的每一个字符
2. 如果当前字符不是空格、制表符或换行符,则标记为一个单词的起始位置
3. 如果当前字符是空格、制表符或换行符,则标记为一个单词的结束位置
4. 如果当前字符是字符串的结束符,则标记为一个单词的结束位置
5. 如果当前位置是单词的结束位置,则单词计数器加1
6. 重复步骤1-5直到遍历完整个字符串
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int countWords(char *str) {
int count = 0;
int isWord = 0; // 标记当前位置是否为一个单词的起始位置
while (*str) {
if (*str != ' ' && *str != '\t' && *str != '\n') {
if (!isWord) { // 如果当前位置不是一个单词的起始位置,则标记为起始位置
isWord = 1;
count++;
}
} else {
isWord = 0; // 如果当前位置是空格、制表符或换行符,标记为单词的结束位置
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
str[strlen(str) - 1] = '\0'; // 去掉fgets读入的换行符
int count = countWords(str);
printf("单词个数为:%d\n", count);
return 0;
}
```
这个程序通过遍历字符串中的每个字符来统计单词个数,同时使用一个标记变量isWord来判断当前位置是否为一个单词的起始位置。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)