Rajeshwar
Rajeshwar

Reputation: 11651

Split a string based on delimeter

My delimeter could be anything except [0-9] ,[A-Z] case insensitive
I therefore would like a way to split my string based on the dynamic delimiter. I am currently using boost but am open to other solutions too.

The code I am currently using involves boost and is this:

vector<string> split_;
boost::split(split,line,boost::is_any_of("\t"));

How can I adjust the above code so it could conform to my delimiter standards ? Is there any other library that could help me accomplish this ? Any suggestions ?

Upvotes: 2

Views: 241

Answers (1)

sehe
sehe

Reputation: 393029

Predicates can be combined:

        !(
            boost::is_from_range('a','z') || 
            boost::is_from_range('A','Z') || 
            boost::is_from_range('0','9')
         )

This magic is due to Boost Lambda library AFAIR. Anyways, you can use it:

Live On Coliru

#include <boost/algorithm/string.hpp>
#include <vector>
#include <iostream>

int main() {
    std::vector<std::string> split_;
    std::string line("one;two#three//four five\r\n"
            "six");
    boost::split(split_,line,
            !(
                boost::is_from_range('a','z') || 
                boost::is_from_range('A','Z') || 
                boost::is_from_range('0','9')
             )
            );

    for(auto const& s : split_)
        std::cout << s << "\n";
}

PS. Consider a regular expression split algorithm though:

Live On Coliru

#include <boost/regex.hpp>
#include <vector>
#include <iostream>

int main()
{
    std::string line("one;two#three//four five\r\n"
            "six");

    boost::regex re("[^a-zA-Z0-9]");
    boost::sregex_token_iterator i(line.begin(), line.end(), re, -1), j;
    std::vector<std::string> split_(i, j);

    for(auto const& s : split_)
        std::cout << s << "\n";
}

Upvotes: 2

Related Questions