使用 C++11 拆分字符串 [英] Split a string using C++11

查看:41
本文介绍了使用 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};
}

这篇关于使用 C++11 拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆