您的位置:首页 > 其它

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

2014-05-30 15:00 801 查看
请你实现一个字符串中单词个数的统计,并按照单词字典序输出单词以及单词的出现个数。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 100
struct 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐