stringstream 将字符串对象与流相关联,允许从字符串中读取,有点类似cin
方法:
- 运算符 << :将字符串添加到 stringstream 对象;
- 运算符 >> :从 stringstream 对象中读取内容;
- stringstream(const string& str):用 str 构造一个 stringstream 对象,
应用场景:
- 计算字符串中的单词个数:
输入:“hello world c plus plus”
输出:5
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string str = "hello world c plus plus";
int count = 0;
stringstream ss(str);
string word;
while (ss >> word)
count++;
cout << count << endl;
system("pause");
return 0;
}
2.打印字符串中单个单词出现的频率
输入:“hello word c plus plus learning c plus plus”
输出:hello-1
world-1
c-2
plus-4
learning-1
#include <iostream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
int main() {
string str = "hello word c plus plus learning c plus plus";
int count = 0;
map<string, int> freq;
stringstream ss(str);
string word;
while (ss >> word)
freq[word]++;
for (auto it = freq.begin(); it != freq.end(); ++it) {
cout << it->first << "->" << it->second << endl;
}
system("pause");
return 0;
}