C++ 编程中的 Stringstream
此示例草案计算特定字符串中的单词总数,并使用 C++ 编程代码中的 stringstream 统计特定单词的总出现次数。stringstream 类将 string 对象与 stream 结合在一起,使你可以像对待 stream 一样浏览 string。此代码将完成两种操作,首先,它将计算单词总数,然后使用 map 迭代器基本方法按顺序计算字符串中各个单词的频率,如下所示:
示例
#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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP