简体   繁体   中英

C++: Elegant way to split string and stuff contents into std::vector

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.

Something like this:

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

?

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.

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 int s. 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

你总是可以使用strtok或string.find()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM