std::vector<std::string> string_split(const std::string& str) {
std::vector<std::string> result;
std::istringstream iss(str);
for (std::string s; iss >> s; )
result.push_back(s);
return result;
}
// Extract the first token
char * token = strtok(string, " ");
// loop through the string to extract all other tokens
while( token != NULL ) {
printf( " %s
", token ); //printing each token
token = strtok(NULL, " ");
}
return 0;
std::string s = "What is the right way to split a string into a vector of strings";
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "
"));
Astringstream associates a string object with a stream allowing you to
read from the string as if it were a stream (like cin). To use stringstream,
we need to include sstream header file.
The stringstream class is extremely useful in parsing input.
in the cp when u need to remove spaces from the string and store it into the
vector or other type of data structure at that it will be your
first choice out there.
Code Example |
---|
Cpp :: how to remove first element from vector c++ |
Cpp :: c++ convert const char* to int |
Cpp :: cpp define function |
Cpp :: SUMOFPROD2 codechef solution |
Cpp :: size of a matrix using vector c++ |
Cpp :: find a number in vector c++ |
Cpp :: function overriding in c++ |
Cpp :: map in c |
Cpp :: vector in c++ |
Cpp :: Subarray with given sum in c++ |
Cpp :: define vector with size and value c++ |
Cpp :: cpp get exception type |
Cpp :: string comparison c++ |
Cpp :: sort strings by length and by alphabet |
Cpp :: substring in c++ |
Cpp :: how creat matrix column in c++ |
Cpp :: friend function in c++ |
Cpp :: loop execution decending order in c |
Cpp :: z transfrom mathlab |
Cpp :: set iterator |
Cpp :: c++ hash map key count |
Cpp :: prime number program c++ |
Cpp :: count number of char in a string c++ |
Cpp :: remove whitespace in cpp |
Cpp :: or in c++ |
Cpp :: c++ linked list |
Cpp :: valid parentheses in cpp |
Cpp :: max circular subarray sum gfg practice |
Cpp :: floyd algorithm |
Cpp :: front priority queue cpp |