-
-
Save locks/258459 to your computer and use it in GitHub Desktop.
string::split c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<string> split(const string& s) | |
{ | |
vector<string> ret; | |
typedef string: ize_type string_size; | |
string_size i = 0; | |
// invariant: we have processed characters [original value of i, i) | |
while (i != s.size()) { | |
// ignore leading blanks | |
// invariant: characters in range [original i, current i) are all spaces | |
while (i != s.size() && isspace(s[i])) | |
++i; | |
// find end of next word | |
string_size j = i; | |
// invariant: none of the characters in range [original j, current j)is a space | |
while (j != s.size() && !isspace(s[j])) | |
j++; | |
// if we found some nonwhitespace characters | |
if (i != j) { | |
// copy from s starting at i and taking j - i chars | |
ret.push_back(s.substr(i, j - i)); | |
i = j; | |
} | |
} | |
return ret; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <class Out> // changed | |
void split(const string& str, Out os) { // changed | |
typedef string::const_iterator iter; | |
iter i = str.begin(); | |
while (i != str.end()) { | |
// ignore leading blanks | |
i = find_if(i, str.end(), not_space); | |
// find end of next word | |
iter j = find_if(i, str.end(), space); | |
// copy the characters in [i, j) | |
if (i != str.end()) | |
*os++ = string(i, j); // changed | |
i = j; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment