// 传入参数
// std::string& s:要分割的字符串
// vector<std::string>& tokens:用来储存分割后的n个字符
// std::string& delimiters:分隔符
void split(const std::string& s, std::vector<std::string>& tokens, const std::string& delimiters)
{
size_t current, previous = 0;
current = s.find(delimiters);
while (current != std::string::npos) {
tokens.push_back(s.substr(previous, current - previous));
previous = current + delimiters.length();
current = s.find(delimiters, previous);
}
if (previous < s.size())
tokens.push_back(s.substr(previous, s.size() - previous));
}
示例一
std::string s = "1,2,3";
vector<std::string> vs;
split(s,vs,",")
/*函数执行后
vs的大小为3
其中
vs[0] = 1; vs[1] = 2; vs[2] = 3;
*/
示例二
std::string s = ",2,";
vector<std::string> vs;
split(s,vs,",")
/*函数执行后
vs的大小为3
其中
vs[0] = "" 为空; vs[1] = 2; vs[2] = "" 为空;
*/
示例三
std::string s = "1,,3";
vector<std::string> vs;
split(s,vs,",")
/*函数执行后
vs的大小为3
其中
vs[0] = 1; vs[1] = "" 为空; vs[2] = 3;
*/