Boost logo

Boost Users :

From: Pavol Droba (droba_at_[hidden])
Date: 2005-01-28 02:11:03


On Thu, Jan 27, 2005 at 03:38:04PM -0800, David Brownell wrote:
> I am attempting to split a string with the string_algo library, using the
> code below. It appears that the split algorithm is designed to split on
> instances of individual characters rather than sequences of characters. Is
> there something I can do to split on a substring? The code below
> illustrates the problem, where I am forces to use the is_any_of predicate
> rather than something that implies equality. It seems like this is a
> trivial use of the algorithm, so there could easily be something that I am
> missing.
> typedef std::vector<boost::iterator_range<char const *> >
> ResultsType;
> ResultsType results;
> static char const STRING[] = "this\r\nis\r\n\r\na test!";
> boost::split(results,
> boost::iterator_range<char const *>(STRING, STRING +
> sizeof(STRING)),
> boost::is_any_of("\r\n")); // The problem is here. I
> would like to be able
> // to use something like
> equals, but split requires
> // a predicate that takes a
> single argument rather than
> // a range.
> for(ResultsType::const_iterator rptr = results.begin();
> rptr != results.end();
> ++rptr)
> std::cout << "'" << std::string(rptr->begin(), rptr->end()) <<
> "'\n";

It is possible to achieve what you want quite easily. However, split algorithm
is not the right tool for this.
Split is a high level wrapper over the split_iterator and it is quite specialized.

So this is the code, that should work for you:

   #include <boost/algorithm/string/find_iterator.hpp>
   #include <boost/algorithm/string/finder.hpp>

   static char const STRING[] = "this\r\nis\r\n\r\na test!";

   typedef boost::split_iterator<const char*> char_split_iterator;

   for(char_split_iterator It=char_split_iterator(STRING, boost::first_finder("\r\n");
        cout << *It << endl;

This example will split the STRING in the tokens, delimited by "\r\n".
Note, that instead of first_finder, you can use any other one. Even the custom one.
Check the documentation for more details.
There is also an example in boost/libs/algorithm/string/example/split_example.cpp



PS: I have not tried to compile the example, so please be patient it there are some errors.

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at