Skip to content

Instantly share code, notes, and snippets.

@chiihuang
Created May 6, 2017 05:13
Show Gist options
  • Save chiihuang/dcb8983ec0a5cf433a49f32b17841ad4 to your computer and use it in GitHub Desktop.
Save chiihuang/dcb8983ec0a5cf433a49f32b17841ad4 to your computer and use it in GitHub Desktop.
How to split a string in C++
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
int main(){
std::string s = "hate, your,,, big, lie,, \nto,us";
std::vector<std::string> elems = split(s, ',');
for(auto e : elems){
std::cout << e << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment