C ++编程中的Stringstream
该示例草案计算了给定字符串中单词的总数,并使用C++编程代码中的stringstream计算特定单词的总出现次数。stringstream类将字符串对象与流配合在一起,使您可以细读字符串,就好像它是流一样。该代码应实现两个功能,首先,它将计算单词总数,然后使用映射迭代器基本方法计算字符串中单个单词的频率,如下所示:
示例
#include <bits/stdc++.h>
using namespace std;
int totalWords(string str){
stringstream s(str);
string word;
int count = 0;
while (s >> word)
count++;
return count;
}
void countFrequency(string st){
map<string, int> FW;
stringstream ss(st);
string Word;
while (ss >> Word)
FW[Word]++;
map<string, int>::iterator m;
for (m = FW.begin(); m != FW.end(); m++)
cout << m->first << " = " << m->second << "\n";
}
int main(){
string s = "Ajay Tutorial Plus, Ajay author";
cout << "Total Number of Words=" << totalWords(s)<<endl;
countFrequency(s);
return 0;
}输出结果
当字符串“AjayTutorialPlus,Ajayauthor”提供给该程序时,输出中单词的总数和频率如下:
Enter a Total Number of Words=5 Ajay=2 Tutorial=1 Plus,=1 Author=1
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短