zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    栈的理解(出、入栈)
    javascript实现可以拖动的层示例(层拖动,兼容IE/FF)
    C# 队列 堆栈
    从0开始做Windows Phone 7开发
    C#写系统日志
    一位软件工程师的6年总结
    向Android模拟器发短信打电话
    office2010激活方法
    常用正则表达式
    JaveScript获得鼠标位置
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12515875.html
Copyright © 2011-2022 走看看