C语言 实现计算句子中的单词数量的计算

用c语言实现判断句子单子数量

编写程序,输出一行字符串中,所有纯英文单词的数目。纯英文单词指的是该单词的所有 字符皆为英文字母(例如:I am a student of 23,需要输出 5)

 

视频讲解见链接:单词计数

 

不废话,上代码

#include<stdio.h>
#include<string.h>
void replace(char a[])//将句子中的标点符号省去
{
    for(int i=0;i<=(int)strlen(a);i++)//首先将标点符号换成空格
        if(a[i]=='.'||a[i]==','||a[i]==':'||a[i]=='?')
            a[i]=' ';//这样会导致句子中出现连续两个的空格形式存在
    for(int i=0;i<=strlen(a);i++)//去掉句子中的连续空格形式
        if(a[i]==' ')
            if(a[i+1]==' ')//若出现连续两个的空格形式
                for(int j=i;j<=strlen(a);j++)//将数组左移,覆盖前面的空格
                    a[j]=a[j+1];
}
void lower(char a[])//将句子当中的所有字母一律改为小写
{
    for(int i=0;i<=(int)strlen(a);i++)
        if(a[i]>='A'&&a[i]<='Z')
            a[i]=a[i]+('a'-'A');
}
int check(char a[])//核查数组,判断数组中存在的非字母“单词”,例如“23”
{
    int fix=0;//初始化勘误变量
    int i=0;//让i在words数组中遍历
    while(a[i]!='\0')
    {
        int flag=0;//定义哨兵flag
        while(a[i]!=' ')
        {
            if(a[i]>='a'&&a[i]<='z')//若单词符合全字母形式,则++i;
                ++i;
            else//否则flag置为1
            {
                flag=1;
                ++i;
            }
        }
        if(flag)//若flag改为了1,说明存在非字母单词
            ++fix;//非字母单词数量加一
        ++i;
    }
    return fix;
}
int count(char a[])//开始数数
{
    int count=0;
    for(int i=0;i<(int)strlen(a);i++)//根据句子当中的空格判断有多少单词的多少
    {
        if(a[i]==' ')
            if(a[i+1]==' ')
            {
                ++count;
                ++i;
            }
            else
                ++count;
        else
            continue;
    }
    int fix=check(a);
    count-=fix;//粗略计算单词以后再减去非单词的数量
    
    return count;
}

int main(){
    char words[100];//"I am student of 23. #¥%¥ and you? are you 23, too?";
    printf("输入一个句子,并且以句号结尾!\n");
    gets(words);
    replace(words);
    lower(words);
    puts(words);
    printf("there have %d words\n",count(words));
}

由于是原创代码,后续应该会在bilibili出视频讲解,方便个位理解代码思想。

posted @ 2020-08-26 18:43  雾漫大武汉  阅读(1006)  评论(0编辑  收藏  举报