diff options
Diffstat (limited to 'tools/splitstring.c')
-rw-r--r-- | tools/splitstring.c | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/tools/splitstring.c b/tools/splitstring.c new file mode 100644 index 0000000..14af577 --- /dev/null +++ b/tools/splitstring.c @@ -0,0 +1,32 @@ +using namespace std; + +class splitstring : public string { + vector<string> flds; +public: + splitstring(const char *s) : string(s) { }; + vector<string>& split(char delim, int rep=0); +}; + +// split: receives a char delimiter; returns a vector of strings +// By default ignores repeated delimiters, unless argument rep == 1. +vector<string>& splitstring::split(char delim, int rep) { + if (!flds.empty()) flds.clear(); // empty vector if necessary + string work = data(); + string buf = ""; + int i = 0; + while (i < work.length()) { + if (work[i] != delim) + buf += work[i]; + else if (rep == 1) { + flds.push_back(buf); + buf = ""; + } else if (buf.length() > 0) { + flds.push_back(buf); + buf = ""; + } + i++; + } + if (!buf.empty()) + flds.push_back(buf); + return flds; +} |