From 01c6088789281005150e39d651aac5078efe477a Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Mon, 28 Oct 2019 18:47:48 +0100 Subject: [PATCH] AK: Add String::contains(String) 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. :^) --- AK/String.cpp | 10 ++++++++++ AK/String.h | 2 ++ Kernel/StdLib.cpp | 31 +++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/AK/String.cpp b/AK/String.cpp index d20193685f..0b97b0da83 100644 --- a/AK/String.cpp +++ b/AK/String.cpp @@ -3,6 +3,10 @@ #include #include +#ifdef KERNEL +extern "C" char* strstr(const char* haystack, const char* needle); +#endif + namespace AK { bool String::operator==(const String& other) const @@ -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()); } + +} + diff --git a/AK/String.h b/AK/String.h index 0db5751810..486d2e381e 100755 --- a/AK/String.h +++ b/AK/String.h @@ -110,6 +110,8 @@ public: return m_impl->to_uppercase(); } + bool contains(const String&) const; + Vector split_limit(char separator, int limit) const; Vector split(char separator) const; String substring(int start, int length) const; diff --git a/Kernel/StdLib.cpp b/Kernel/StdLib.cpp index 822dc33cd1..491db3d458 100644 --- a/Kernel/StdLib.cpp +++ b/Kernel/StdLib.cpp @@ -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(haystack); +} + [[noreturn]] void __cxa_pure_virtual() { ASSERT_NOT_REACHED();