stringstream 处理字符串

在刷leetcode 过程中,C++一直没有比较好的方法来分割字符串,尤其对于带有很明显的分隔符比如.,\,等

我一般的做法都是用两个下标来标识一段子字符串,然后substr()来做进一步处理。

最近学习了用stringstream来处理字符串,类似iosteam,fsteam,使得操作string就像操作输入流一样。

71. 简化路径

思路

对于文件路径有很明显的分隔符/,类似的对于IP地址分隔符.

  • 用输入字符串来初始化stringstream对象
  • while循环提取子字符串,根据情况判断
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
string simplifyPath(string path) {
vector<string> st;
stringstream is(path);
string res,temp;
while(getline(is,temp,'/')){
// cout<<"temp: "<<temp<<endl;
if(temp==""||temp==".") // 处理// /./情况
continue;
else if(temp==".."){
if(st.size())st.pop_back();
}

else st.push_back(temp);
}
for(auto str:st){
res+="/"+str;
}
if(res.empty()) return "/";
return res;
}

下面的snippet code 用来处理类似"dog cat mouse ..."字符串

1
2
3
4
stringstream raw(str);
vector<string> strs;
string line;
while (raw >> line) strs.push_back(line);