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

请你实现一个字符串中单词个数的统计,并按照单词字典序输出单词以及单词的出现个数。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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值