您的位置:首页 > 其它

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

2012-09-13 11:53 253 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐