Skip to content

Commit

Permalink
AK: Add String::contains(String)
Browse files Browse the repository at this point in the history
This is just a wrapper around strstr() for now. There are many better
ways to search for a string within a string, but I'm just adding a nice
API at the moment. :^)
  • Loading branch information
awesomekling committed Oct 28, 2019
1 parent fe83d50 commit 01c6088
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
10 changes: 10 additions & 0 deletions AK/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
#include <AK/StringBuilder.h>
#include <stdarg.h>

#ifdef KERNEL
extern "C" char* strstr(const char* haystack, const char* needle);
#endif

namespace AK {

bool String::operator==(const String& other) const
Expand Down Expand Up @@ -313,4 +317,10 @@ bool String::match_helper(const StringView& mask) const
return (mask_ptr == mask_end) && !*string_ptr;
}

bool String::contains(const String& needle) const
{
return strstr(characters(), needle.characters());
}

}

2 changes: 2 additions & 0 deletions AK/String.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ class String {
return m_impl->to_uppercase();
}

bool contains(const String&) const;

Vector<String> split_limit(char separator, int limit) const;
Vector<String> split(char separator) const;
String substring(int start, int length) const;
Expand Down
31 changes: 31 additions & 0 deletions Kernel/StdLib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,37 @@ int memcmp(const void* v1, const void* v2, size_t n)
return 0;
}

int strncmp(const char* s1, const char* s2, size_t n)
{
if (!n)
return 0;
do {
if (*s1 != *s2++)
return *(const unsigned char*)s1 - *(const unsigned char*)--s2;
if (*s1++ == 0)
break;
} while (--n);
return 0;
}

char* strstr(const char* haystack, const char* needle)
{
char nch;
char hch;

if ((nch = *needle++) != 0) {
size_t len = strlen(needle);
do {
do {
if ((hch = *haystack++) == 0)
return nullptr;
} while (hch != nch);
} while (strncmp(haystack, needle, len) != 0);
--haystack;
}
return const_cast<char*>(haystack);
}

[[noreturn]] void __cxa_pure_virtual()
{
ASSERT_NOT_REACHED();
Expand Down

0 comments on commit 01c6088

Please sign in to comment.