11

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.

user231536
  • 2,661
  • 4
  • 33
  • 45
  • 3
    possible duplicate of [How do I tokenize a string in C++?](http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c) - see answer from @KeithB – Steve Townsend Oct 29 '10 at 21:08
  • 18
    How about some of the examples from the following: http://www.codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant. The String Toolkit Library makes complex string processing in C++ simple and easy. –  Dec 08 '10 at 05:32

4 Answers4

8

Something like this:

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

?

sbi
  • 219,715
  • 46
  • 258
  • 445
4

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
  • 348,265
  • 75
  • 913
  • 977
  • Is there a way of using boost::tokenizer with arbitrary tokens? It seems to work with characters like `' ', ',', '(', ')', ';'`. Is there a way to use for example `'m'` as a token? – FreelanceConsultant Mar 05 '13 at 15:59
1

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

ssube
  • 47,010
  • 7
  • 103
  • 140
0

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

theninjagreg
  • 1,616
  • 2
  • 12
  • 17