找出一句话中出现次数最多的单词

#include   <string>
#include   <iostream>
#include   <map>
using namespace std;

int nMax = 0;
int j = 0;
bool bEnd = false;
char buf[20] = {'0'};

bool isWorld(char chr)
{
	if ((chr >= 'a' && chr <= 'z') || (chr >= 'A'&& chr <= 'Z'))
		return true;
		return false;
}

void GetWorld(map<string, int> &test,char chr)
{
	bEnd = false;
	if(!isWorld(chr))
	bEnd =true;
	if (bEnd && j)
	{
		string str;
		str.assign(buf,j);
		cout << str << " ";
		if(test.find(str)==test.end())
		{
			test[str] = 1;
		}
		else
		{
			test[str]++;
		}
		if (nMax < test[str])
			nMax = test[str];
		memset(buf, '0', sizeof(buf));
		j = 0;
	}
	if (isWorld(chr))
	{
		buf[j] = chr;
		j++;
	}
}

int main()
{
	char *CWord = ", ,this, ,is a test test hao are you ,";
	map<string, int> MapWorld;
	int i = 0;
	while(!isWorld(CWord[i]))
		i++;
	while (CWord[i])
	{
		GetWorld(MapWorld,CWord[i]);
		i++;
	}
	cout << endl;
	map<string, int>::iterator itr = MapWorld.begin();
	for(itr;itr!=MapWorld.end();itr++)
	{
		if(itr->second == nMax)
			cout<<itr->first<<endl;
	}
	getchar();
	return 0;
}


下面这个类似的题目
有一段文本,统计其中的单词数。例如:
As a technology , "HailStorm" is so new that it is still only known by itscode name.
注意:单词间的间隔不一定是一个空格。
答:可执行程序代码如下,假设该文本已存入text这个数组里。

void main()
{
  char text[1000]={"As a technology , 'HailStorm' is so new that it is still only known by its code name."};
  int i=0,count=0;
  bool flag=true;
  while (text[i]&&i<1000) 
  {
    if (text[i]==' ') 
    {
      flag=true;
    }
    else if (flag==true && ((text[i]>='a'&&text[i]<='z')||(text[i]>='A'&&text[i]<='Z'))) 
    {  // 前有空格,接着出现字母,表示出现一个单词。
      count++;
      flag=false;
    }
    i++;
  }
  cout<<count;
}




 

转载于:https://www.cnblogs.com/byfei/archive/2012/09/13/3112202.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值