C language counts the number of different words

Count how many words (not repeated) in a sentence entered, the sentence has only lowercase letters and spaces

Insert picture description here

analysis

Traverse the input sentence from the beginning, assign each word to the string variable t, if there is no such word in the words string array, count count+1, and copy the word to the words array

Code

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int count=0;//全局变量
int x=0;//全局变量
void append(char (*p)[30],char *t)//定义函数,实现单词是否存在的判断,若不存在则计数加一,并复制单词到数组
{
    
    
    int flag=0,i;
    for(i=0;i<100;i++)
    {
    
    
        if(strcmp(t,p[i])==0)
           {
    
    
                flag=1;
           }
    }
    if(flag==0)
    {
    
    
        count++;
        strcpy(p[x++],t);
    }

}
int main()
{
    
       char words[100][30]={
    
    '\0'};
    char s[101]={
    
    '\0'};
    char t[30];
    int i,j,m=0;
    gets(s);
    for(i=0;i<strlen(s);i++)
    {
    
    
        if(s[i]!=' ')
        {
    
    
            for(j=i;s[j]>='a'&&s[j]<='z';j++)
            {
    
    
                t[m++]=s[j];
            }
            i=j;
            t[m]='\0';
            m=0;
            append(words,t);//调用函数
        }
    }
    printf("%d",count);
    return 0;
}

Guess you like

Origin blog.csdn.net/SingDanceRapBall/article/details/94838760