字符串单词计数

要求:输入一个字符串,统计每个单词的个数。单词间用空格隔开,可多个空格,写出自己认为高效的算法。

例如:输入:I love love China
输出为:
I: 1
love: 2
China: 1

#include <stdio.h>
#include<iostream>
#include <string>

struct struct_words
{
	char word[20];
	int count;
};
int main() {
	char string[100];
	char c;
	struct_words words[20];
	int i = 0, k = 0, ws = 0;

	for (; i < 20; i++) {    //初始化结构体
		words[i].word[0] = '\0';
		words[i].count = 0;
	}
	puts("please input words.");
	gets_s(string);
	puts("=============开始取词================");

	i = 0;
	do {
		c = string[i];
		if (c != ' ' && c != '\0') {
			words[k].word[ws] = c;
			words[k].count = 1;
			ws++;
		}
		else {
			words[k].word[ws] = '\0';

			ws = 0;
			k++;
		}
		i++;
	} while (c != '\0');


	puts("=========== 合并相同的单词 ==============");
	for (i = 0; words[i].word[0] != '\0'; i++) {
			for (k = i; words[k].word[0] != '\0'; k++) {
				if (strcmp(words[i].word, words[k].word) == 0
					&& words[k].count == 1) {
					words[k].count--;
					words[i].count++;
				}
			}
	}

	puts("=============== End ==============");
	for (i = 0; words[i].word[0] != '\0'; i++) {
		if (words[i].count != 0)
			printf("%s:\t\t%d\n", words[i].word, words[i].count);
	}
	system("pause");
	return(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值