c++ split string on 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 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);
Example 4: split a string based on a delimiter in c++
void tokenize(string &str, char delim, vector<string> &out)
{
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != string::npos)
{
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
int main()
{
string s="a;b;c";
char d=';';
vector<string> a;
tokenize(s,d,a);
for(auto it:a) cout<<it<<" ";
return 0;
}