Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string in C++ using 2 delimiters '+' & '-"

i am trying to split a string with 2 delimiters '+' and '-' in C++ using a string find a delimiter...

can anyone give me a go around...

Using

str.find(delimiter)

example :

a+b-c+d

Output Required: a b c d

Thanks in advance

like image 520
rolling.stones Avatar asked Dec 09 '22 12:12

rolling.stones


1 Answers

Using std::string::substr and std::string::find

    std::vector<std::string> v ; //Use vector to add the words

    std::size_t prev_pos = 0, pos;
    while ((pos = str.find_first_of("+-", prev_pos)) != std::string::npos)
    {
        if (pos > prev_pos)
            v.push_back(str.substr(prev_pos, pos-prev_pos));
        prev_pos= pos+1;
    }
    if (prev_pos< str.length())
        v.push_back(str.substr(prev_pos, std::string::npos));

Or if you use boost it will be lot easier

#include <boost/algorithm/string.hpp>

std::vector<std::string> v;
boost::split(v, line, boost::is_any_of("+-"));
like image 107
P0W Avatar answered Dec 11 '22 01:12

P0W