1.stringstream
头文件<sstream>
继承关系:
使用示例:
// swapping ostringstream objects
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::stringstream ss;
ss << 100 << ' ' << 200;
int foo,bar;
ss >> foo >> bar;
std::cout << "foo: " << foo << '\n';
std::cout << "bar: " << bar << '\n';
return 0;
}
//输出
//foo: 100
//bar: 200
1.1 构造函数
可以使用一个string对象构造stringstream。
stringstream没有复制构造函数copy constructor。
2. 继承自istream的函数
2.1 常用函数之 >>
>>
用于提取数字或字符串。
2.2 常用函数之 getline
Extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character).
从stream中提取c风格的字符串到s中,直到遇到分隔符delim或者达到n个字符(包括终止的null)
分隔符默认为换行符,如果需要自定义,可以使用第二个函数
2.3 常用函数之 ignore
忽略delim之前的所有字符。
// istream::ignore example
#include <iostream> // std::cin, std::cout
int main () {
char first, last;
std::cout << "Please, enter your first name followed by your surname: ";
first = std::cin.get(); // get one character
std::cin.ignore(256,' '); // ignore until space
last = std::cin.get(); // get one character
std::cout << "Your initials are " << first << last << '\n';
return 0;
}
//输出:
//Please, enter your first name followed by your surname: John Smith
//Your initials are JS
3. 继承自ostream的函数
比较常用的就是<<
,用法简单不做介绍。
4. 解决LeetCode71.简化路径
//思路:首先将整个字符串以"/"分割。然后逐一判断每个子串。
if(str == "." || str == ""){
continue;
}
else if(str == ".." && !stack.empty()){
stack.pop();
}
else if(str != "."){
stack.push(str);
}
//将栈中的所有子串拼接,注意顺序,当然也可以不使用栈,使用vector或者list存储子串都可以
class Solution {
public:
string simplifyPath(string path) {
stringstream is(path);
string tmp;
list<string> strlist;
while(getline(is, tmp, '/')){ //以/为分割符找到所有子串
if(tmp == "" || tmp == "."){
continue;
}
else if(tmp == ".." && !strlist.empty()){
strlist.pop_back();
}
else if(tmp != ".."){
strlist.push_back(tmp);
}
}
string res;
for(auto s : strlist){
res += ("/" + s);
}
if(res.empty()){
return "/";
}
return res;
}
};
5. 获取输入数字放入数组中,数字以空格为间隔
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
string input;
getline(cin, input);
stringstream ss(input);
int val;
vector<int> array;
while (ss >> val) {
array.push_back(val);
}
for (auto& val : array) {
cout << val << " ";
}
cout << endl;
return 0;
}