字符串的分割

字符串的分割

示例一

使用C++2.0,模仿php中explode方法的功能。

#include 
#include 
#include 
// MARK: - The definition of explode
// The given delimiter is limited to a single char only
const std::vector explode(const std::string &src, const char &c) {
    std::vector result;
    result.clear();
    if (src.empty()) {
        return result;
    }
    std::string buffer{""};
    for (auto n : src) {
        if (n != c) {
            buffer += n;
        } else if(n == c && !buffer.empty()){
            result.emplace_back(buffer);
            buffer.clear();
        }
    }
    if(!buffer.empty()) {
        result.emplace_back(buffer);
        buffer.clear();
    }
    return result;
}

// MARK: - Main 入口
int main(int argc, char *argv[])
{
    std::string text {"We can write a explode fuction using C++."};
    std::vector res{explode(text, ' ')};
    for(auto elem: res)
    std::cout << elem << std::endl;
    return 0;
}

示例2

利用正则方法 std::regex,std::regex类的使用可以参考
https://blog.csdn.net/qq_28087491/article/details/107608569

#include 
#include 
#include 
#include 

std::vector split(const std::string& src, const std::string& regex) {
    // passing -1 as the submatch index parameter performs splitting
    std::regex re(regex);
    std::sregex_token_iterator
        first{src.begin(), src.end(), re, -1},
        last;
    return {first, last};
}

// MARK: - Main 入口
int main(int argc, char *argv[])
{
    std::string text {"We can write a explode fuction using C++."};
    
    std::vector res{split(text, " ")};
    for(auto elem: res)
        std::cout << elem << std::endl;
    return 0;
}

更多的分割方法

https://stackoverflow.com/questions/9435385/split-a-string-using-c11

你可能感兴趣的:(字符串的分割)