diff --git a/core/AmUtils.cpp b/core/AmUtils.cpp index d2482df8..e45feeef 100644 --- a/core/AmUtils.cpp +++ b/core/AmUtils.cpp @@ -972,23 +972,33 @@ unsigned int get_random() return r; } + // Explode string by a separator to a vector -vector explode(string s, string e) { - vector ret; - int iPos = s.find(e, 0); - int iLen = e.length(); - while (iPos > -1) { - if (iPos != 0) - ret.push_back(s.substr(0, iPos)); - s.erase(0, iPos+iLen); - iPos = s.find(e, 0); +// see http://stackoverflow.com/questions/236129/c-how-to-split-a-string +std::vector explode(const string& s, const string& delim, + const bool keep_empty) { + vector result; + if (delim.empty()) { + result.push_back(s); + return result; } - if (s != "") - ret.push_back(s); - return ret; + string::const_iterator substart = s.begin(), subend; + while (true) { + subend = search(substart, s.end(), delim.begin(), delim.end()); + string temp(substart, subend); + if (keep_empty || !temp.empty()) { + result.push_back(temp); + } + if (subend == s.end()) { + break; + } + substart = subend + delim.size(); + } + return result; } + // Warning: static var is not mutexed // Call this func only in init code. // diff --git a/core/AmUtils.h b/core/AmUtils.h index b6293cb3..f12d8e60 100644 --- a/core/AmUtils.h +++ b/core/AmUtils.h @@ -286,7 +286,7 @@ void init_random(); unsigned int get_random(); /** Explode string by a separator to a vector */ -std::vector explode(string s, string e); +std::vector explode(const string& s, const string& delim, const bool keep_empty = false); /** add a directory to an environement variable */ void add_env_path(const char* name, const string& path);