c语言编写int fun,统计一行字符串中单词个数作为函数值返回。规定所有单词有小写字母组成
时间: 2024-02-01 15:16:05 浏览: 36
下面是一个简单的 C 语言函数实现,可以统计一行字符串中单词个数并作为函数值返回:
```c
#include <stdio.h>
int countWords(char *str) {
int count = 0;
int i = 0;
// 遍历字符串中的每个字符
while (str[i] != '\0') {
// 如果当前字符是单词的第一个字符,或者前一个字符是空格
if ((i == 0 || str[i - 1] == ' ') && str[i] >= 'a' && str[i] <= 'z') {
count++;
}
i++;
}
return count;
}
int main() {
char str[] = "hello world! this is a test string.";
int wordCount = countWords(str);
printf("The number of words in the string is %d.\n", wordCount);
return 0;
}
```
函数 `countWords` 接受一个指向字符串的指针,并返回该字符串中单词的数量。它使用一个循环遍历字符串中的每个字符,并使用两个条件来确定当前字符是否属于一个新的单词。如果是一个新的单词,则将计数器增加。最后,函数返回计数器的值。
注意,该函数只能处理由小写字母组成的单词,并且只能处理单个空格字符作为单词之间的分隔符。如果字符串中包含其他类型的字符或多个空格字符,则此实现将无法正确计算单词数。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)