26
* Splits a string using a delimiter
28
* @param s the string to split
29
* @param delim the delimitir to use
30
* @param elems the string vector to populate
33
Util::split(const std::string &s, char delim, std::vector<std::string> &elems)
29
Util::split(const string& src, char delim, vector<string>& elementVec, bool fuzzy)
35
std::stringstream ss(s);
38
while(std::getline(ss, item, delim))
39
elems.push_back(item);
37
// Simple case: we want to enforce the value of 'delim' strictly
40
std::stringstream ss(src);
42
while(std::getline(ss, item, delim))
43
elementVec.push_back(item);
47
// Fuzzy case: Initialize our delimiter string based upon the caller's plus
48
// a space to allow for more flexibility.
49
string delimiter(" ");
51
// Starting index into the string of the first token (by definition, if
52
// we're parsing a string, there is at least one token).
53
string::size_type startPos(0);
54
// string::find_first_of() looks for any character in the string provided,
55
// it is not treated as a sub-string, so regardless of where the space or
56
// comma is or how many there are, the result is the same.
58
string::size_type endPos = str.find_first_of(delimiter);
59
while (endPos != string::npos)
61
// Push back the current element starting at startPos for
62
// (endPos - startPos) characters. std::string takes care of
64
elementVec.push_back(string(str, startPos, endPos - startPos));
65
// Index of the next element after any delimiter characters. Same
66
// caveat applies to find_first_not_of() that applies to
67
// find_first_of(); endPos tells it where to start the search.
68
string::size_type nextPos = str.find_first_not_of(delimiter, endPos);
69
// Erase the part of the string we've already parsed.
70
str = str.erase(startPos, nextPos - startPos);
71
// Look for the next delimiter. If there isn't one, we bail out.
72
endPos = str.find_first_of(delimiter);
74
// Regardless of whether we initially had one element or many, 'str' now
76
elementVec.push_back(str);