Reputation: 7183
In C++, I'd like to something similar to:
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).
Upvotes: 1
Views: 706
Reputation: 1923
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;
}
Upvotes: 1
Reputation: 477040
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;
Upvotes: 3