使用 C++11 拆分字符串

2021-12-28 00:00:00 string split c++ c++11

使用 C++11 拆分字符串的最简单方法是什么?

What would be easiest method to split a string using c++11?

我看过这篇帖子所使用的方法,但我觉得使用新标准应该有一种不那么冗长的方法.

I've seen the method used by this post, but I feel that there ought to be a less verbose way of doing it using the new standard.

我想要一个 vector 作为结果并且能够分隔单个字符.

I would like to have a vector<string> as a result and be able to delimitate on a single character.

推荐答案

std::regex_token_iterator 基于正则表达式执行通用标记化.对单个字符进行简单拆分可能会也可能不会过度,但它有效并且不太冗长:

std::regex_token_iterator performs generic tokenization based on a regex. It may or may not be overkill for doing simple splitting on a single character, but it works and is not too verbose:

std::vector<std::string> split(const string& input, const string& regex) {
    // passing -1 as the submatch index parameter performs splitting
    std::regex re(regex);
    std::sregex_token_iterator
        first{input.begin(), input.end(), re, -1},
        last;
    return {first, last};
}

相关文章