c++字符串分割

c++字符串的spilit

字符串分割是处理字符串的常见问题,以下提供几种解决方案。

初始版本

#include <iostream>
#include <string>
#include <regex>
#include <vector>

// 采用正则版本
std::vector<std::string> split(std::string &text)
{
    std::regex ws_re("\s+");  // white space
    return std::vector<std::string>(std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1), std::sregex_token_iterator());
}

//优雅版本
void split(const std::string &text, std::vector<std::string> &tokens, const std::string &delimiter = " ") {
    std::string::size_type lastPos = text.find_first_not_of(delimiter, 0);
    std::string::size_type pos = text.find_first_of(delimiter, lastPos);
    while (std::string::npos != pos || std::string::npos != lastPos) {
        tokens.emplace_back(text.substr(lastPos, pos - lastPos));
        lastPos = text.find_first_not_of(delimiter, pos);
        pos = text.find_first_of(delimiter, lastPos);
    }
}

void test() {
    std::string str{"quick brown fox"};
    std::vector<std::string> t1 = split(str);
    std::cout << "regex 版本
";
    for (auto s : t1) std::cout << s << std::endl;

    std::vector<std::string> t2;
    split(str, t2);
    std::cout << "优雅版本
";
    for (auto s : t2) std::cout << s << std::endl;
}

int main() {
    test();
}

新版本,使用stream,该版本能只能分割空格字符,后续可以改进分割

std::vector<std::string> split(const std::string& text) {
    std::istringstream iss(text);
    std::vector<std::string> res((std::istream_iterator<std::string>(iss)),
                                  std::istream_iterator<std::string>());
    return res;
}

非标准,但对任意delimiter都能用,接口清晰

std::vector<std::string> split(const std::string& s, const char delimiter)
{
    std::vector<std::string> tokens;
    std::string tokens;
    std::istringstream tokenStream(s);
    while(std::getline(tokenStream, token, delimiter))
    {
        tokens.push_back(token);
    }
    return tokens;
}
原文地址:https://www.cnblogs.com/codemeta-2020/p/12515875.html