Browse Source

base: new string functions.

Add String.split(char) to split into an array, and add a simple
char const * + lol::String free operator.
undefined
Sam Hocevar 8 years ago
parent
commit
8044747ac3
2 changed files with 54 additions and 0 deletions
  1. +23
    -0
      src/lol/base/string.h
  2. +31
    -0
      src/t/base/string.cpp

+ 23
- 0
src/lol/base/string.h View File

@@ -228,6 +228,24 @@ public:
&& memcmp(C() + count() - s.count(), s.C(), s.count()) == 0;
}

array<String> split(char c = '\n') const
{
array<String> 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;


+ 31
- 0
src/t/base/string.cpp View File

@@ -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 */


Loading…
Cancel
Save