C语言统计一行字符串中单词的个数
时间: 2023-05-26 18:06:05 浏览: 78
以下是一个简单的C语言程序,用于统计一行字符串中单词的个数:
```c
#include <stdio.h>
#define MAX_LENGTH 1000
int main() {
char str[MAX_LENGTH];
int wordCount = 0, i;
// 从控制台读取输入的字符串
printf("请输入字符串:\n");
fgets(str, MAX_LENGTH, stdin);
// 统计单词个数
for (i = 0; str[i] != '\0'; i++) {
// 如果当前字符是空格或者换行符,则表示一个单词的结束,计数器加1
if (str[i] == ' ' || str[i] == '\n') {
wordCount++;
}
}
// 输出单词个数
printf("字符串中共有%d个单词\n", wordCount);
return 0;
}
```
程序中的思路很简单:遍历字符串中每个字符,如果当前字符是空格或者换行符,则表示一个单词的结束,计数器加1。最后输出计数器的值即可。
相关问题
c语言指针编写统计一个字符串中单词的个数
要统计一个字符串中单词的个数,你可以使用指针来遍历字符串,并根据空格或其他分隔符判断单词的边界。下面是一个示例代码:
```c
#include <stdio.h>
int countWords(const char* str) {
int count = 0;
int isWord = 0; // 标记当前是否在单词中
while (*str != '\0') {
if (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r') {
// 当前字符为空格或制表符或换行符或回车符,表示单词结束
isWord = 0;
} else if (!isWord) {
// 当前字符不是空格或制表符或换行符或回车符,且上一个字符是空格或制表符或换行符或回车符,表示进入一个新的单词
isWord = 1;
count++;
}
str++;
}
return count;
}
int main() {
const char* str = "Hello world! How are you?";
int wordCount = countWords(str);
printf("Number of words: %d\n", wordCount);
return 0;
}
```
在上面的代码中,`countWords`函数接受一个字符指针作为参数,并使用指针遍历字符串。它使用`isWord`变量来标记当前是否在单词中。当遇到空格、制表符、换行符或回车符时,将`isWord`设为0表示单词结束。当遇到非空格、制表符、换行符或回车符的字符,并且上一个字符是空格、制表符、换行符或回车符时,将`isWord`设为1表示进入一个新的单词,并且单词计数器`count`加1。最后,返回单词的个数。
在`main`函数中,我们定义了一个字符串,并调用`countWords`函数来统计该字符串中的单词个数,并将结果打印出来。
请注意,这里的分隔符仅包括空格、制表符、换行符和回车符。如果你的需求中还包括其他分隔符,你需要相应地修改代码来适应你的需求。
c语言统计一行文本中单词的个数
您好!感谢您的提问!
关于您的问题,可以使用C语言编写程序来统计一行文本中单词的个数。一种简单的实现方式是,遍历字符串中的每个字符,当遇到空格、制表符、回车等分隔符时,将单词计数器加1。同时,需要判断是否在单词中间,如果是,则跳过后续的分隔符。
以下是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int count_words(const char* s)
{
int count = 0;
int in_word = 0;
while (*s != '\0') {
if (isalnum(*s)) {
if (!in_word) {
count++;
in_word = 1;
}
} else {
in_word = 0;
}
s++;
}
return count;
}
int main()
{
char text[] = "hello, world! this is a test.";
int count = count_words(text);
printf("The number of words is %d\n", count);
return 0;
}
```
该程序输出:
```
The number of words is 6
```
希望可以帮助您解决问题!如果还有其他问题,可以继续向我提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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_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)