Browse Source

Add string::split().

tags/v2.0.0
Andrew Belt 3 years ago
parent
commit
234890faf6
2 changed files with 41 additions and 0 deletions
  1. +11
    -0
      include/string.hpp
  2. +30
    -0
      src/string.cpp

+ 11
- 0
include/string.hpp View File

@@ -67,6 +67,17 @@ std::string join(const TContainer& container, std::string seperator = "") {
return s;
}

/** Splits a string into a vector of tokens.
Tokens do not include the separator string.
Examples:
split("a+b+c", "+") // {"a", "b", "c"}
split("abc", "+") // {"abc"}
split("a++c", "+") // {"a", "", "c"}
split("", "+") // {}
split("abc", "") // {"a", "b", "c"}
*/
std::vector<std::string> split(const std::string& s, const std::string& seperator);


#if defined ARCH_WIN
/** Performs a Unicode string conversion from UTF-16 to UTF-8.


+ 30
- 0
src/string.cpp View File

@@ -205,6 +205,36 @@ bool CaseInsensitiveCompare::operator()(const std::string& a, const std::string&
}


std::vector<std::string> split(const std::string& s, const std::string& separator) {
// Special case of empty string
if (s == "")
return {};

std::vector<std::string> v;
// Special case of empty separator
if (separator == "") {
for (char c : s) {
std::string token(1, c);
v.push_back(token);
}
return v;
}

size_t sepLen = separator.size();
size_t start = 0;
size_t end;
while ((end = s.find(separator, start)) != std::string::npos) {
std::string token = s.substr(start, end - start);
v.push_back(token);
// Don't include delimiter
start = end + sepLen;
}

v.push_back(s.substr(start));
return v;
}


#if defined ARCH_WIN
std::string UTF16toUTF8(const std::wstring& w) {
if (w.empty())


Loading…
Cancel
Save