string分割
方法一:使用find()和substr()/迭代器.
用字符分割字符串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| void Stringsplit(const string& str, const char split, vector<string>& res) { if (str == ""){ return }; string strs = str + split; size_t pos = strs.find(split); while (pos != strs.npos) { string temp = strs.substr(0, pos); res.push_back(temp); strs = strs.substr(pos + 1, strs.size()); pos = strs.find(split); } }
|
或者
1 2 3 4 5 6 7 8 9 10 11 12
| void stringSplit(const std::string &str, const char sep, std::vector<std::string>& res) { std::string::const_iterator cur = str.begin(); std::string::const_iterator end = str.end(); std::string::const_iterator next = find(cur, end, sep); while (next != end) { res.emplace_back(cur, next); cur = next + 1; next = std::find(cur, end, sep); } res.emplace_back(cur, next); return; }
|
用字符串分割字符串
整个字符串splits作为分隔符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| void Stringsplit(const string& str, const string& splits, vector<string>& res) { if (str == "") return; string strs = str + splits; size_t pos = strs.find(splits); int step = splits.size();
while (pos != strs.npos) { string temp = strs.substr(0, pos); res.push_back(temp); strs = strs.substr(pos + step, strs.size()); pos = strs.find(splits); } }
|
方法二:使用istringstream.
优点:代码更简洁。缺点:引入了字符串流,性能低于前两种