在一些和字符串相关的算法中经常需要使用字符串分割,以下是一种简单的实现方试。
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
istringstream str(" this is a text");
string out;
while (str.good()) {
getline(str, out, ' '); //从str读取字符串到out中,遇到空格便停止
if (!out.empty()) //如果原字符串中有连续的空格out会为空
cout << out << endl;
}
}
无意间看到大神是这样写的
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
istringstream str(" this is a text");
string out;
while (str >> out) {
cout << out << endl;
}
}
输出:
this
is
a
text