istringstream/stringstream(用法相同,函数不同)
istringstream
是 C++ 中的一个类,它可以将一个字符串按照某个分隔符进行分隔,并以流的形式输出每一个分隔出来的字符串。默认为 ‘ ’区分单词。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
istringstream iss(s); // 用 istringstream 分隔单词
string word;
while (iss >> word) {
cout << word << endl; // 输出分隔出来的单词
}
return 0;
}
iss >> word
表示从 iss
中读取一个单词,并将其存储到 word
中
iss >> word
这个表达式的返回值是一个 istringstream
类型的对象,因此可以将其作为 while
循环的条件,只要能够读取到一个单词就会一直循环下去。输出的结果就是分隔出来的单词 "hello" 和 "world"。
如果需要用其他 字符 或者 字母 来区分单词,那么可以将其传递给 stringstream
或 istringstream
构造函数中的 delim
参数,例如
vector<string> uncommonFromSentences(string s1, string s2) {
unordered_map<string, int> count;
string s = s1 + "|" + s2; // 合并字符串并用 '|' 分隔单词
stringstream ss(s);
string word;
while (getline(ss, word, '|')) { // 使用 '|' 分隔单词
count[word]++;
}
vector<string> res;
for (auto& [word, freq] : count) {
if (freq == 1) {
res.push_back(word);
}
}
return res;
}
注意!while处的使用方法发生了变化。不是 >>, 而是getline