实现一个字符串中单词个数的统计,并按照单词字典序输出单词以及单词的出现个数。使用strsep

来源:互联网 发布:sql语句更改表名 编辑:程序博客网 时间:2024/05/16 03:40
请你实现一个字符串中单词个数的统计,并按照单词字典序输出单词以及单词的出现个数。Hint:a.不考虑标点符号.b.如果有单词是大写将单词转换为小写统计c.句子中除了单词全部都是空格,没有其他特殊字符。
Input:”I love you do you love me”
Output:
do 1
I 1
love 2
me 1

you 2


#include<stdio.h>#include<stdio.h>#include<string.h>#include<stdlib.h>#define MAX 100struct WORD{char str[40];int num;}words[MAX];//linux 下没有该函数,大写字母转为小写字母char *myStrlwr( char *s){char *str=s;while(*str!='\0'){if(*str>='A' && *str <='Z')*str=*str+32;str++;}return s;}//统计字符串出现的次数int statistics(char * source,struct  WORD words[]){char *p[MAX];int in=0;while( (p[in]=strsep(&source, " ")) !=NULL){in++;}int i,j;int count=0; //统计当前的单词数for(i=0; i < in ; i++){for(j=0; j < count ;j++){if( strcmp(p[i] , words[j].str)==0){words[j].num++;break;}}if(j==count){strncpy(words[count].str, p[i], 40);words[count].num++;count++;}}return count;}int cmp(const void *a,const void *b){return strcmp( (*(struct WORD*)a).str, (*(struct WORD *) b).str);}//对字符串按字典序排序void sort(struct  WORD words[],int len){qsort(words,len,sizeof(struct  WORD),cmp);}//显示void print(struct  WORD  words[],int len){int i;for(i=0;i<len;i++)printf("%s\t%d\n",words[i].str,words[i].num);printf("\n");}int main(){char str[100]="I love you do you love me";printf("输入字符串为:");printf("%s\n", str);char *lowercase = myStrlwr(str);//将字符串转换成小写形式int len = statistics(lowercase,words);printf("字符串中的单词个数: %d\n",len);sort(words,len);print(words,len);return 0;}


0 0
原创粉丝点击