diff --git a/src/lol/base/string.h b/src/lol/base/string.h index 696c0b5b..301d1125 100644 --- a/src/lol/base/string.h +++ b/src/lol/base/string.h @@ -228,6 +228,24 @@ public: && memcmp(C() + count() - s.count(), s.C(), s.count()) == 0; } + array split(char c = '\n') const + { + array ret; + for (int start = 0; start < m_count; ) + { + char const *tmp = strchr(C() + start, c); + if (!tmp) + { + ret.push(String(C() + start)); + break; + } + int size = tmp - C() - start; + ret.push(String(C() + start, size)); + start += size + 1; + } + return ret; + } + bool is_alpha() const { for (int i = 0; i < m_count; i++) @@ -312,6 +330,11 @@ public: static String vformat(char const *format, va_list ap); }; +inline String operator +(char const *sz, String const &s) +{ + return String(sz) + s; +} + inline bool operator ==(char const* sz, String const &s) { return s == sz; diff --git a/src/t/base/string.cpp b/src/t/base/string.cpp index f3e58011..51bd13d9 100644 --- a/src/t/base/string.cpp +++ b/src/t/base/string.cpp @@ -240,6 +240,37 @@ lolunit_declare_fixture(string_test) lolunit_assert(s1 < s4); lolunit_assert(!(s4 < s1)); } + + lolunit_declare_test(string_split) + { + auto l1 = String("abc").split(); + lolunit_assert(l1.count() == 1); + lolunit_assert(l1[0] == "abc"); + + auto l2 = String("\nabc").split(); + lolunit_assert(l2.count() == 2); + lolunit_assert(l2[0] == ""); + lolunit_assert(l2[1] == "abc"); + + auto l3 = String("abc\n").split(); + lolunit_assert(l3.count() == 2); + lolunit_assert(l3[0] == "abc"); + lolunit_assert(l3[1] == ""); + + auto l4 = String("\n\n").split(); + lolunit_assert(l4.count() == 3); + lolunit_assert(l4[0] == ""); + lolunit_assert(l4[1] == ""); + lolunit_assert(l4[2] == ""); + + auto l5 = String("abc\nde\n\nf\n").split(); + lolunit_assert(l5.count() == 5); + lolunit_assert(l5[0] == "abc"); + lolunit_assert(l5[1] == "de"); + lolunit_assert(l5[2] == ""); + lolunit_assert(l5[3] == "f"); + lolunit_assert(l5[4] == ""); + } }; } /* namespace lol */