用C语言求一个字符串中有多少个单词,单词之间用空格分隔,但两个单词之间可能有多个空格
时间: 2023-12-26 21:17:08 浏览: 28
可以使用以下代码来实现:
```c
#include <stdio.h>
#include <ctype.h>
int count_words(char *str) {
int count = 0, is_word = 0;
while (*str) {
if (isspace(*str)) {
is_word = 0;
} else if (!is_word) {
is_word = 1;
count++;
}
str++;
}
return count;
}
int main() {
char str[] = " This is a test string. ";
int count = count_words(str);
printf("The number of words in the string is: %d\n", count);
return 0;
}
```
在 `count_words` 函数中,使用一个 `is_word` 变量来记录当前是否在一个单词中。遍历字符串,如果遇到空格,则将 `is_word` 设为 0;如果遇到一个非空格字符并且当前不在一个单词中,则将 `is_word` 设为 1,并将单词计数器加 1。最后返回计数器的值即可。
相关问题
用C语言编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。
以下是两种用C语言编写程序统计一行字符中单词个数的例子:
1.使用while循环和if语句逐个字符检索,统计单词数。
```c
#include <stdio.h>
int main() {
int sum=0;//字符总数
char a;//单字检索
while(1)//死循环在使用时注意与break搭配
{
scanf("%c",&a);
if(a=='\n') break;
else if(a!=' ')//确保开始时符号不是空格或回车
{
sum++;//检索首字母,统计单词数
while(1)//单词检索
{
scanf("%c",&a);
if(a==' '||a=='\n')//检索到词尾,这样就形成了两空格夹一个单词的形式, break; //解决了単词间空格个数不定问题
}
}
if(a=='\n') break;//只有当单词后为回车时结束两层循环
}
printf("%d",sum);
return 0;
}
```
2.使用字符数组和for循环逐个字符判断,统计单词数。
```c
#include <stdio.h>
int main() {
char a[1000];//字符数组
gets(a);//获取字符串
int i;//循环变量
int l;//记录字符串长度
int num = 0;//单词数量
for(i=0;a[i]!='\0';i++);//记录字符串长度
l=i;
for(i=0;i<l;i++)//循环判断
{
if(a[i]!=' ' && a[i+1]==' ')//符合[?][空格]的情况
num++;
if(a[i]!=' ' && a[i+1]=='\0')//符合[?]['\0']的情况
num++;
}
printf("%d\n",num);
return 0;
}
```
c语言编写int fun,统计一行字符串中单词个数作为函数值返回。规定所有单词有小写字母组成
下面是一个简单的 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` 接受一个指向字符串的指针,并返回该字符串中单词的数量。它使用一个循环遍历字符串中的每个字符,并使用两个条件来确定当前字符是否属于一个新的单词。如果是一个新的单词,则将计数器增加。最后,函数返回计数器的值。
注意,该函数只能处理由小写字母组成的单词,并且只能处理单个空格字符作为单词之间的分隔符。如果字符串中包含其他类型的字符或多个空格字符,则此实现将无法正确计算单词数。