Skip to content

Instantly share code, notes, and snippets.

@hitigon
Last active August 29, 2015 13:56
Show Gist options
  • Save hitigon/9039293 to your computer and use it in GitHub Desktop.
Save hitigon/9039293 to your computer and use it in GitHub Desktop.
C++ string split
//naive way to implement C++ string split
//In the worst case, it costs O(n^2) time
int split(string tokens[], string str, string d) {
int i = 0;
size_t n = str.length();
if (d.length() > n || str.find(d) == string::npos) return -1;
size_t pos;
while (i < n && (pos = str.find(d)) != string::npos) {
tokens[i] = str.substr(0, pos);
str = str.substr(pos + 1);
i++;
}
tokens[i] = str;
return i + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment