tags:

views:

122

answers:

4

I would like to split a string along whitespaces, and I know that the tokens represent valid integers. I would like to transform the tokens into integers and populate a vector with them.

I could use boost::split, make a vector of token strings, then use std::transform.

What is your solution? Using boost is acceptable.

+2  A: 

You can use Boost.Tokenizer. It can easily be wrapped up into an explode_string function that takes a string and the delimiter and returns a vector of tokens.

Using transform on the returned vector is a good idea for the transformation from strings to ints; you can also just pass the Boost.Tokenizer iterator into the transform algorithm.

James McNellis
+6  A: 

Something like this:

std::istringstream iss("42 4711 ");
std::vector<int> results( std::istream_iterator<int>(iss)
                        , std::istream_iterator<int>() );

?

sbi
@Maciej: Thanks!
sbi
A: 

You could always use strtok or string.find().

theninjagreg
+1  A: 

Use Boost's string algorithm library to split the string into a vector of strings, then std::for_each and either atoi or boost::lexical_cast to turn them into ints. It's likely to be far simpler than other methods, but may not have the greatest performance due to the copy (if someone has a way to improve it and remove that, please comment).

std::vector<int> numbers;

void append(std::string part)
{
    numbers.push_back(boost::lexical_cast<int>(part));
}

std::string line = "42 4711"; // borrowed from sbi's answer
std::vector<std::string> parts;
split(parts, line, is_any_of(" ,;"));
std::for_each(parts.being(), parts.end(), append);

Roughly.

http://www.boost.org/doc/libs/1_44_0/doc/html/string_algo.html http://www.boost.org/doc/libs/1_44_0/libs/conversion/lexical_cast.htm

peachykeen