该示例草案计算了给定字符串中单词的总数,并使用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; }
输出结果
当字符串“ Ajay Tutorial Plus,Ajay author ”提供给该程序时,输出中单词的总数和频率如下:
Enter a Total Number of Words=5 Ajay=2 Tutorial=1 Plus,=1 Author=1