有没有办法在C ++中用多个分隔符标记字符串?在C#中我会做到:
string[] tokens = "adsl, dkks; dk".Split(new [] { ",", " ", ";" }, StringSplitOptions.RemoveEmpty);
答案 0 :(得分:3)
使用boost :: tokenizer。它支持多个分隔符。
事实上,你甚至不需要boost :: tokenizer。如果您想要的只是一个分割,请使用boost :: split。文档有一个例子: http://www.boost.org/doc/libs/1_42_0/doc/html/string_algo/usage.html#id1718906
答案 1 :(得分:2)
这样的事情会发生:
void tokenize_string(const std::string &original_string, const std::string &delimiters, std::vector<std::string> *tokens)
{
if (NULL == tokens) return;
size_t pos_start = original_string.find_first_not_of(delimiters);
size_t pos_end = original_string.find_first_of(delimiters, pos_start);
while (std::string::npos != pos_start)
{
tokens->push_back(original_string.substr(pos_start, pos_end - pos_start));
pos_start = original_string.find_first_not_of(delimiters, pos_end);
pos_end = original_string.find_first_of(delimiters, pos_start);
}
}
答案 2 :(得分:0)
这是我的版本(未经过严格测试):
std::vector<std::string> split(std::string const& s,
std::vector<std::string> const& delims)
{
std::vector<std::string> parts;
std::vector<std::pair<std::string::size_type, std::string::size_type>> poss;
poss.reserve(delims.size());
std::string::size_type beg = 0;
for(;;)
{
poss.clear();
std::string::size_type idx = 0;
for(auto const& delim: delims)
{
if(auto end = s.find(delim, beg) + 1)
poss.emplace_back(end - 1, idx);
++idx;
}
if(poss.empty())
break;
std::sort(std::begin(poss), std::end(poss));
auto old_beg = beg;
for(auto pos: poss)
{
parts.emplace_back(std::begin(s) + beg,
std::begin(s) + old_beg + pos.first);
beg = pos.first + delims[pos.second].size();
}
}
if(beg < s.size())
parts.emplace_back(std::begin(s) + beg, std::end(s));
return parts;
}