diff options
| author | Dan Albert <danalbert@google.com> | 2015-03-19 13:24:26 -0700 |
|---|---|---|
| committer | Dan Albert <danalbert@google.com> | 2015-03-23 10:23:11 -0700 |
| commit | 47328c96d91ca71b57b8976df2df1fe51579a955 (patch) | |
| tree | 149e519906cb870b960e7e48facd7222a7ec7232 /base/strings.cpp | |
| parent | d69a1c502e11d3be052d9c0bb20f0c7762428925 (diff) | |
| download | core-47328c96d91ca71b57b8976df2df1fe51579a955.tar.gz core-47328c96d91ca71b57b8976df2df1fe51579a955.tar.bz2 core-47328c96d91ca71b57b8976df2df1fe51579a955.zip | |
Update string Split API.
Return a new vector rather than appending to the parameter.
Delimiters are also a string rather than a character. Split on any
character in the string.
Change-Id: I039b332ace5578590df9e7ca0e8fa3db28db30a3
Diffstat (limited to 'base/strings.cpp')
| -rw-r--r-- | base/strings.cpp | 40 |
1 files changed, 26 insertions, 14 deletions
diff --git a/base/strings.cpp b/base/strings.cpp index 224a46f5b..5f7eccc3f 100644 --- a/base/strings.cpp +++ b/base/strings.cpp @@ -16,27 +16,39 @@ #include "base/strings.h" +#include <stdlib.h> + #include <string> #include <vector> namespace android { namespace base { -void Split(const std::string& s, char separator, - std::vector<std::string>* result) { - const char* p = s.data(); - const char* end = p + s.size(); - while (p != end) { - if (*p == separator) { - ++p; - } else { - const char* start = p; - while (++p != end && *p != separator) { - // Skip to the next occurrence of the separator. - } - result->push_back(std::string(start, p - start)); - } +#define CHECK_NE(a, b) \ + if ((a) == (b)) abort(); + +std::vector<std::string> Split(const std::string& s, + const std::string& delimiters) { + CHECK_NE(delimiters.size(), 0U); + + std::vector<std::string> split; + if (s.size() == 0) { + // Split("", d) returns {} rather than {""}. + return split; } + + size_t base = 0; + size_t found; + do { + found = s.find_first_of(delimiters, base); + if (found != base) { + split.push_back(s.substr(base, found - base)); + } + + base = found + 1; + } while (found != s.npos); + + return split; } std::string Trim(const std::string& s) { |
