0%

C++字符串分割

字符串分割方式汇总

string.find

1
2
3
4
5
6
7
8
9
10
11
12
std::string s = "scott,tiger,mushroom";
std::string delimiter = ",";

size_t pos = 0;
std::string token;
std::vector<string> v;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
v.push_back(token);
s.erase(0, pos + delimiter.length());
}
v.push_back(s);

boost::split()

注意split在处理多字符分隔符的时候会有一些更奇妙的行为。
此外要处理结果中的空字符串。

1
2
3
4
#include <boost/algorithm/string.hpp>
std::string line = "scott,tiger,mushroom";
std::vector<std::string> v;
boost::split(v,line,boost::is_any_of(","));

strotk

1
2
3
4
5
6
7
std::string str = "scott,tiger,mushroom";
char *token = strtok(str.data(), ",");
std::vector<std::string> v;
while (token != NULL) {
token = strtok(NULL, " ");
v.push_back(std::string(token));
}