stringstream 将字符串对象与流相关联,允许从字符串中读取,有点类似cin
方法:
应用场景:
#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; }