本文以leetcode上的一道简单算法题(http://oj.leetcode.com/problems/reverse-words-in-a-string/)来说明istringstream在初始化时会过滤掉首尾的空格。
题目大意是将一个string类型的字符串,按逐个单词倒置。string的首尾可能有零个或多个空格,每个单词之间由一个或多个空格分隔。例如:
Given s = " the sky is blue
",
return "blue is sky the
".
输入有可能出现空串:“”,或只包含若干个空格的串:“ ”。
此题如果用C写比较麻烦,用C++的vector<string>和istringstream处理则方便许多。AC的代码如下:
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
vector<string> svec;
istringstream iss(s);
string str;
while(iss>>str)
svec.push_back(str);
s.clear();
vector<string>::reverse_iterator rit;
if(!svec.empty()) {
for(rit=svec.rbegin();rit!=svec.rend()-1;++rit){
s.append(*rit).append(" ");
}
s.append(*rit);
}
cout<<s<<"hhhaha"<<endl;
}
};
可以验证,如果s=“ abc def ghi ”,istringstream对象iss接收s后会过滤首尾的空格,
需要注意的是,如果s=“”或s=“ ”,则iss为空,svec也为空。
关于istringstream常见的用法还有另一种情况值得注意,就是从外部文件中按行读取数据:
void read_data ( const string &filename ) {
ifstream infile; //文件输入流
string line,str;
istringstream iss; //string输入流
infile.open( filename );
while( getline( infile,line ) ){ //getline按行读取文件数据 ,line的末尾会保存一个换行符
iss.clear();
iss( line ); //ss的末尾也会随之保存一个换行符
while( ss >> str ) {
/*具体代码省略*/
/* 注意ss最后会给str一个换行符,如果不希望保留这个换行符,应做相应的删除处理 */
}
}
infile.close();
}