写一个c语言程序,统计一个字符中单词的个数

如题所述

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int WordCount(char a[])
{
     int n= strlen(a);
     int cnt=0;
     int i;
     for(i=0;i<n;i++)
     {
         if(!isalpha(a[i]) && i-1>=0 && isalpha(a[i-1]))
         {
             cnt++;
         }
     }    
     return cnt;
}
int main()
{
    char a[1024];
    while(gets(a))
    {
         printf("%d\n",WordCount(a));              
    }
    return 0;    
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-03-02
#include<stdio.h>
#include<string.h>
int main()
{
char c[1000];
gets(c);
int count=1;
for(int i=0;i<strlen(c);i++)
if(c[i]==' ')count++;
printf("%d\n",count);
}追答

不知道你的字符串中都有哪些字符,所以我默认只有字母和空格,代码就是这样。还有问题吗?

追问

不需要空格

追答

我知道,这个代码是统计只含有字母和空格的字符串中单词的个数的

你运行一下,看能用不

追问

哦哦,好的,谢谢

本回答被提问者采纳
第2个回答  推荐于2016-03-02
#include<stdio.h>
#include<string.h>
int main()
{
char c[1000];
gets(c);
int count=1;
for(int i=0;i<strlen(c);i++)
if(c[i]==' ')count++;
printf("%d\n",count);
}追答

不知道你的字符串中都有哪些字符,所以我默认只有字母和空格,代码就是这样。还有问题吗?

追问

不需要空格

追答

我知道,这个代码是统计只含有字母和空格的字符串中单词的个数的

你运行一下,看能用不

追问

哦哦,好的,谢谢

本回答被提问者采纳
相似回答
大家正在搜