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出視頻講解,方便個位理解代碼思想。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM