本文介绍了C ++ - 通过regex拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将您的输入包含多个分隔符(您的案例中的空格)


I want to split std::string by regex.

I have found some solutions on Stackoverflow, but most of them are splitting string by single space or using external libraries like boost.

I can't use boost.

I want to split string by regex - "\\s+".

I am using this g++ version g++ (Debian 4.4.5-8) 4.4.5 and i can't upgrade.

解决方案

You don't need to use regular expressions if you just want to split a string by multiple spaces. Writing your own regex library is overkill for something that simple.

The answer you linked to in your comments, Splitting a string in C++, can easily be changed so that it doesn't include any empty elements if there are multiple spaces.

std::vector<std::string> &split(const std::string &s, char delim,std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        if (item.length() > 0) {
            elems.push_back(item);
        }
    }
    return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

By checking that item.length() > 0 before pushing item on to the elems vector you will no longer get extra elements if your input contains multiple delimiters (spaces in your case)

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

08-19 15:12
查看更多