将 std::string 拆分为 vector<string> 的正确方法

新手上路,请多包涵

将字符串拆分为字符串向量的正确方法是什么?分隔符是空格或逗号。

原文由 softwarematter 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

对于空格分隔的字符串,您可以这样做:

 std::string s = "What is the right way to split a string into a vector of strings";
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

输出:

 What
is
the
right
way
to
split
a
string
into
a
vector
of
strings


包含逗号和空格的字符串

struct tokens: std::ctype<char>
{
    tokens(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        typedef std::ctype<char> cctype;
        static const cctype::mask *const_rc= cctype::classic_table();

        static cctype::mask rc[cctype::table_size];
        std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask));

        rc[','] = std::ctype_base::space;
        rc[' '] = std::ctype_base::space;
        return &rc[0];
    }
};

std::string s = "right way, wrong way, correct way";
std::stringstream ss(s);
ss.imbue(std::locale(std::locale(), new tokens()));
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

输出:

 right
way
wrong
way
correct
way

原文由 Nawaz 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我的变体,类似于 PHP 中的爆炸函数,我们提供给定的字符串和分隔符列表。

 std::vector< std::string > explode(const std::string& data, const std::string& delimiters) {
    auto is_delim = [&](auto & c) { return delimiters.find(c) != std::string::npos; };
    std::vector< std::string > result;
    for (std::string::size_type i(0), len(data.length()), pos(0); i <= len; i++) {
        if (is_delim(data[i]) || i == len) {
            auto tok = data.substr(pos, i - pos);
            if ( !tok.empty() )
                result.push_back( tok );
            pos = i + 1;
        }
    } return result;
}

使用示例

std::string test_delimiters("hello, there is lots of, delimiters, that may be even together,  ");

auto dem_res = explode(test_delimiters, " ,"); // space or comma

for (auto word : dem_res) {
    std::cout << word << '\n';
} std::cout << "end\n";

输出:

 hello
there
is
lots
of
delimiters
that
may
be
even
together
end

原文由 Vitaly Protasov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题