Take the 2-minute tour ×

In C++, I'd like to something similar to:

Split on substring

However, I'd like to specify more than one substring to split on. For example, I'd like to split on "+", "foo", "ba" for the string "fda+hifoolkjba4" into a vector of "fda", "hi", "lkj", "4". Any suggestions? Preferably within STL and Boost (I'd rather not have to incorporate the Qt framework or additional libraries if I can avoid it).

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

I would go with regular expressions, either from <regex> or <boost/regex.hpp>; the regular expression you need would be something like (.*?)(\+|foo|ba) (plus the final token).

Here's a cut-down example using Boost:

  std::string str(argv[1]);

  boost::regex r("(.*?)(\\+|foo|ba)");
  boost::sregex_iterator rt(str.begin(), str.end(), r), rend;

  std::string final;

  for ( ; rt != rend; ++rt)
    std::cout << (*rt)[1] << std::endl;
    final = rt->suffix();
  std::cout << final << std::endl;
share|improve this answer
Thanks, I'm not too keen on using boost regex because the compiled libraries don't work so well on my mac. I can get them to work, but I need to point to my dynlib file (either in the executable directory or in a specified directory - not exactly ideal for distributing my work in standalone form), but that's an issue for a different question. –  daj Dec 14 '11 at 14:01
@daj: well, get a modern compiler then and use <regex> from the standard library :-) Same interface, just change boost to std. –  Kerrek SB Dec 14 '11 at 14:02
That's great, I didn't realize it was in the standard library now. I do prefer Boost's split_regex() function for doing this (since iteration is replaced with a one-liner), which doesn't seem to have been added :-( –  daj Dec 14 '11 at 14:46
add comment

I suggest using regular expression support in boost. See here for an example.

here is a sample code that can split the string:

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

using namespace std;    

int main()

    boost::regex re("(\\+|foo|ba)");
    std::string s("fda+hifoolkjba4");

    boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
    boost::sregex_token_iterator j;
    while (i != j) {
       std::cout << *i++ << " ";
    std::cout << std::endl;
    return 0;
share|improve this answer
add comment

Your Answer


