在处理字符串分割相关的问题时,由于没有“Split”函数,C++与Java,C#等相比较会较笨拙,可以采用stringstream(即字符串流)的方法类比 Split 函数对字符串做处理。注:默认分隔符为空格。
stringstream 的基本操作:
- clear() — to clear the stream
- str() — to get and set string object whose content is present in stream.
- operator << — add a string to the stringstream object.
- operator >> — read something from the stringstream object,
Example1:
int countWords(string str)
{
// breaking input into word using string stream
stringstream s(str); // Used for breaking words
string word; // to store individual words
int count = 0;
while (s >> word)
count++;
return count;
}
Example2: LeetCode 71. Simplify Path
C++ code:
class Solution {
public:
string simplifyPath(string path) {
stringstream ss(path);
string tmp, res;
vector<string> str;
while(getline(ss, tmp, '/'))
{
if(tmp=="" || tmp==".") continue;
if(tmp==".." && !str.empty()) str.pop_back();
else if(tmp!="..") str.push_back(tmp);
}
if(str.empty()) return "/";
for(int i=0; i<str.size(); ++i)
res += '/' + str[i];
return res;
}
};