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 :: function in struct c++ |
Cpp :: how to add external library in clion |
Cpp :: image shapes in opencv c++ |
Cpp :: how to add c++14 in sublime text |
Cpp :: array to string c++ |
Cpp :: how to play sounds in c++ |
Cpp :: integer to char c++ |
Cpp :: power function c++ |
Cpp :: c++ contains |
Cpp :: cpp class constructor |
Cpp :: letter occurrence in string c++ |
Cpp :: automatic legend matlab |
Cpp :: how to slice vector in c++ |
Cpp :: login system with c++ |
Cpp :: how to print in new lines in C++ |
Cpp :: c++ find object in vector by attribute |
Cpp :: how to generate number in c++ |
Cpp :: 31. Next Permutation leetcode solution in c++ |
Cpp :: cpp template |
Cpp :: class operator overloading c++ |
Cpp :: break statement in c++ program |
Cpp :: preorder |
Cpp :: int max in c++ |
Cpp :: C++ fibo |
Cpp :: cpp oop |
Cpp :: c++ map lookup |
Cpp :: potato |
Cpp :: C++ if...else...else if statement |
Cpp :: statements |
Cpp :: time complexity of best sort algorithm |