Browse Source

Added IndexOf and LastIndexOf methods in class String

legacy
Benlitz benlitz 11 years ago
parent
commit
4b98ef04a6
2 changed files with 110 additions and 1 deletions
  1. +60
    -0
      src/lol/base/string.h
  2. +50
    -1
      test/unit/string.cpp

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

@@ -117,6 +117,66 @@ public:
return String(&(*this)[start], count);
}

int IndexOf(const char token) const
{
for (int i = 0; i < Count(); ++i)
{
if ((*this)[i] == token)
return i;
}
return -1;
}

int IndexOf(const char* token) const
{
int token_len = strlen(token);
if (Count() < token_len)
return -1;

for (int i = 0; i < Count() - token_len + 1; ++i)
{
int j = 0;
for (; j < token_len; ++j)
{
if ((*this)[i + j] != token[j])
break;
}
if (j == token_len)
return i;
}
return -1;
}

int LastIndexOf(const char token) const
{
for (int i = Count() - 1; i >= 0; --i)
{
if ((*this)[i] == token)
return i;
}
return -1;
}

int LastIndexOf(const char* token) const
{
int token_len = strlen(token);
if (Count() < token_len)
return -1;

for (int i = Count() - token_len; i >= 0; --i)
{
int j = 0;
for (; j < token_len; ++j)
{
if ((*this)[i + j] != token[j])
break;
}
if (j == token_len)
return i;
}
return -1;
}

inline String operator +(String const &s) const
{
String ret(*this);


+ 50
- 1
test/unit/string.cpp View File

@@ -148,7 +148,56 @@ LOLUNIT_FIXTURE(StringTest)
String s5 = "World";
LOLUNIT_ASSERT(s4 == s5);
}
};

LOLUNIT_TEST(IndexOf)
{
String s1 = "Hello World";
int i1 = s1.IndexOf('H');
int i2 = s1.IndexOf('W');
int i3 = s1.IndexOf('d');

int i4 = s1.IndexOf("Hello");
int i5 = s1.IndexOf("World");
int i6 = s1.IndexOf("lo");
int i7 = s1.IndexOf("Hello World");
int i8 = s1.IndexOf("Sup' dude");

LOLUNIT_ASSERT(i1 == 0);
LOLUNIT_ASSERT(i2 == 6);
LOLUNIT_ASSERT(i3 == 10);
LOLUNIT_ASSERT(i4 == i1);
LOLUNIT_ASSERT(i5 == i2);
LOLUNIT_ASSERT(i6 == 3);
LOLUNIT_ASSERT(i7 == 0);
LOLUNIT_ASSERT(i8 == -1);
}

LOLUNIT_TEST(LastIndexOf)
{
String s1 = "Hello World";
int i1 = s1.LastIndexOf('H');
int i2 = s1.LastIndexOf('W');
int i3 = s1.LastIndexOf('d');

int i4 = s1.LastIndexOf("Hello");
int i5 = s1.LastIndexOf("World");
int i6 = s1.LastIndexOf("lo");
int i7 = s1.LastIndexOf("Hello World");
int i8 = s1.LastIndexOf("Sup' dude");
int i9 = s1.LastIndexOf('l');
int i10 = s1.LastIndexOf('o');

LOLUNIT_ASSERT(i1 == 0);
LOLUNIT_ASSERT(i2 == 6);
LOLUNIT_ASSERT(i3 == 10);
LOLUNIT_ASSERT(i4 == i1);
LOLUNIT_ASSERT(i5 == i2);
LOLUNIT_ASSERT(i6 == 3);
LOLUNIT_ASSERT(i7 == 0);
LOLUNIT_ASSERT(i8 == -1);
LOLUNIT_ASSERT(i9 == 9);
LOLUNIT_ASSERT(i10 == 7);
}};

} /* namespace lol */


Loading…
Cancel
Save