C语言统计不同单词数

统计输入的一个句子中有多少单词(不重复的),句子只有小写字母跟空格

在这里插入图片描述

分析

从头遍历输入的句子,把每个单词赋给字符串变量t,如果words字符串数组中没有该单词,则计数count+1,并把单词复制到words数组中

代码

#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;
}

猜你喜欢

转载自blog.csdn.net/SingDanceRapBall/article/details/94838760