• 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;
    }
  • 相关阅读:
    Tomcat 启动很慢?
    CentOS 下 安装 JDK8
    CentOS 下 安装 nginx
    SpringBoot 之 打war包
    Spring MVC处理异常有3种方法
    springboot 之 使用jetty web容器
    IDEA 中,编译后不拷贝 mybatis 配置的 mapper 的 xml 文件
    js 鼠标点击页面出现文字
    PHP 获取天气
    js 必须为字母或下划线, 一旦创建不能修改
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12515875.html
Copyright © 2020-2023  润新知