Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

e.g. split on " "

message1
message2 

=>

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
311 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 << '
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...