统计单词数

Problem I: 统计单词数
Time Limit: 1 Sec Memory Limit: 32 MB
Submit: 8166 Solved: 3669
[Submit][Status][Web Board]
Description
给一个句子,统计这个句子中有多少个单词。单词可能包含大写字母、小写字母、数字和其他符号,单词之间用空白符或标点符号隔开。

Input
有多组数据,每个句子占一行,句子长度不超过1000个字符,到文件尾结束。

Output
每个句子对应一个整数,代表这个句子中有多少个单词,每个整数占一行

Sample Input
Meep…meep!
How are you?
Sample Output
2
3
HINT

Append Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int find(char c)
{
    int i,j,k,flag=0;
    char a[52];
    for(i=0;i<26;i++)
    {
        a[i]='A'+i;
    }
    for(j=0;j<26;j++)
    {
        a[26+j]='a'+j; //为数组a赋值:A-Z,a-z
    }
    for(k=0;k<52;k++)//遍历数组a,看c是否在数组a中
        {
            if(c==a[k])
            {flag=1;
            return 1;}
        }
    if(flag==0)
        return 0;
}
int main()
{
    char s[1005];
    int i,j,len,num;
    while(gets(s)!=NULL)
    {
        num=0;
        len=strlen(s);
        for(i=0,j=1;j<len;i++,j++)
        {
             if(find(s[i])==1&&find(s[j])==0)
                num++;
                //现在这个字符是字母,下一个不是
        }
        if(find(s[len-1])==1)
                num++;
          //当最后一个字符为字母后面没有字符标点。单独拎出来
        printf("%d\n",num);
    }
    return 0;
}

flag的那块儿代码

for(k=0;k<52;k++)
        {
            if(c==a[k])
            return 1;
        }
    if(k==52)//一定是52,循环最后一次k=52不满足,跳出循环
        return 0;
for(k=0;k<52;k++)
        {
            if(c==a[k])
            return 1;
        }
        return 0;//这里不写循环条件也是对的,因为前面没有return1,跳出了循环,所以才进行到这里。

ctype.h里边儿的isspace(空白符,是则返回非零值)和ispunct(用来检测一个字符是否为标点符号或特殊字符,若是返回非零值)函数好像也可以用但是没做出来

猜你喜欢

转载自blog.csdn.net/weixin_43737185/article/details/84639491