c++中如何统计一个单词出现了几次?

RT
这是我写的,但是运行不了,不知道while里该写什么,请人指导!

去c++吧提问不能用vc6.0,还请问我该下载哪一版的vc比较好?

很简单啊。
string str;
cin>>str; 这里可能会有问题,比如 空格或换行 会截断你的输入。
int n = 0, k = 0;
do{
int r = str.find("xxx", k);
if(r == string::npos) break;
++n;
k = r + strlen("xxx");
}while(true);
对于一般的单词都是可以找到。对于特殊情况,比如 aaa ,假如aa算一个单词,这里有几个aa呢?如果是1个,上面的代码就是对的,如果算2个,那么修改 k = r + 1;追问

谢谢你的回答,我想再问的是如果要避免string截断输入的话,应该换哪一种方式?换了的话是不是就不能用string::size_type了??

追答

http://baike.baidu.com/link?url=EfZzbDbBjb49vOV35i8GSdMRWowbwaE5eXYjWq8WQ3UvD8GzdmokLJ5UwVJ4UIXHfys7OxHvGNqVvNl4ArzHgK
这个例子就是,你自己去指定截断符。
string::size_type 其实和int差不多。使用int最好

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-27
#include <iostream>#include <string>using namespace std;
int _tmain(int argc, _TCHAR* argv[]){ cout << "Please insert a sentence." << endl; string sentence; cin >> sentence; size_t finding; finding=sentence.find("heqiwen"); size_t length; length = sentence.size(); int times = 0; while (finding != string::npos) { times++; if(length - 7 < 7) { break; }
sentence = sentence.substr(finding + 7, length); finding = sentence.find("heqiwen");
}
if(times == 0) { cout << "There is no heqiwen in this sentence" << endl; } else { cout << "There is " << times << " heqiwen in this sentence." << endl; }
system("pause"); return 0;}
第2个回答  2013-12-27
老实话, VC6.0不行跟不上了, 现在的老师教课都是vc6.0 没那么多限制,而且这个软件很简单,不像现在的VC, 集成的东西多, 但是你要想,现在电脑都什么配置? VC6.0 1998年出来的, 现在还在用,vc有2005 2008 2010 2013 不知道有没有2012 这些都是我用过的, vc6.0我没用过,听说是语法不规范什么的, 你现在就算VC6.0通过 了 你到高版本去一试,错误一大片,你都不知道什么意思, vc6.0还是不要用了, 换个高版本的,写代码也很智能追问

原来如此啊.....那么大学教的时候用vc6.0岂不是误导吗....

第3个回答  2013-12-27
怎么可能不能用6.0.
string::size_type stPos = 0;
while((finding = sentence.find("heqiwen", stPos) != string::npos)
{
stPos += strlen("heqiwen");
++times;
}
相似回答