Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

split

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.

like image 927
user231536 Avatar asked Oct 29 '10 21:10

user231536


People also ask

Is there a split function in C++?

There is no built-in split() function in C++ for splitting strings, but there are numerous ways to accomplish the same task, such as using the getline() function, strtok() function, find() and erase() functions, and so on. This article has explained how to use these functions to split strings in C++.

How do you parse a string in CPP?

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token. The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.


1 Answers

Something like this:

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

?

like image 135
sbi Avatar answered Oct 27 '22 13:10

sbi