在字符串操作中,常常遇到按照某个字符将字符串按照某种方式(逗号,空格等等)分割成很多子字符串。在python中会经常遇到,对于项目中也常常用到。C++没有专门的函数,需要实现一下这个功能如下:
参见源码:
void split(std::vector<std::string>& split_strs, std::string const& str, char delim = ' ', bool keep_empty = false)
{
std::size_t new_tok = 0;
std::size_t cur_pos = 0;
for (; cur_pos < str.size(); ++cur_pos)
{
if (str[cur_pos] == delim)
{
std::string token = str.substr(new_tok, cur_pos - new_tok);
if (keep_empty || !token.empty())
split_strs.push_back(token);
new_tok = cur_pos + 1;
}
}
if (keep_empty || new_tok < str.size())
split_strs.push_back(str.substr(new_tok));
}
这份代码,将str字符串,按照delim的方式分割成多个字符串,然后存入split_strs,用于后续操作。