split string c++ by space code example
Example 1: cpp split string by space
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;
}
Example 2: string split by space c++
char * token = strtok(string, " ");
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, " ");
}
return 0;
Example 3: c++ split at character
std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;
while(std::getline(test, segment, '_'))
{
seglist.push_back(segment);
}
Example 4: c++ split string by several space
std::string s = "split on whitespace ";
std::vector<std::string> result;
std::istringstream iss(s);
for(std::string s; iss >> s; )
result.push_back(s);