C++ - Split string by regex

前端 未结 4 1232
鱼传尺愫
鱼传尺愫 2020-12-05 13:47

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 o

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 14:50

    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, Split a string in C++?, can easily be changed so that it doesn't include any empty elements if there are multiple spaces.

    std::vector &split(const std::string &s, char delim,std::vector &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 split(const std::string &s, char delim) {
        std::vector 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)

提交回复
热议问题