Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split on substring

Tags:

c++

How would I split a string based on another substring in a simple way?

e.g. split on "\r\n"

message1\r\nmessage2 

=>

message1
message2

From what I've been able to find both boost::tokenizer and boost::split only operates on single characters.

EDIT:

I'm aware that I could do this by using std::string::find and std::string::substr and have a loop etc... but thats not what I mean by "simple".

like image 924
ronag Avatar asked Sep 17 '10 21:09

ronag


1 Answers

Although boost::split indeed takes a predicate that operates on characters, there's a boost string algorithm that can split on substrings:

#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <boost/algorithm/string/iter_find.hpp>
#include <boost/algorithm/string/finder.hpp>
int main()
{
    std::string input = "message1foomessage2foomessage3";

    std::vector<std::string> v;
    iter_split(v, input, boost::algorithm::first_finder("foo"));

    copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, " "));
    std::cout << '\n';
}
like image 89
Cubbi Avatar answered Sep 27 '22 19:09

Cubbi