AK: Fix StringUtils::contains() case insensitive search

It would incorrectly return false if needle was at the end the string.
This commit is contained in:
Linus Groh 2020-11-12 23:44:32 +00:00 committed by Andreas Kling
parent b1754bf8f8
commit d3ee3fc68a
Notes: sideshowbarker 2024-07-19 02:29:19 +09:00
2 changed files with 9 additions and 8 deletions

View file

@ -247,19 +247,18 @@ bool contains(const StringView& str, const StringView& needle, CaseSensitivity c
return memmem(str_chars, str.length(), needle_chars, needle.length()) != nullptr;
auto needle_first = to_lowercase(needle_chars[0]);
size_t slen = str.length() - needle.length();
for (size_t si = 0; si < slen; si++) {
for (size_t si = 0; si < str.length(); si++) {
if (to_lowercase(str_chars[si]) != needle_first)
continue;
size_t ni = 1;
while (ni < needle.length()) {
if (to_lowercase(str_chars[si + ni]) != to_lowercase(needle_chars[ni]))
for (size_t ni = 0; si + ni < str.length(); ni++) {
if (to_lowercase(str_chars[si + ni]) != to_lowercase(needle_chars[ni])) {
si += ni;
break;
ni++;
}
if (ni == needle.length())
if (ni + 1 == needle.length())
return true;
}
}
return false;
}

View file

@ -203,6 +203,8 @@ TEST_CASE(contains)
EXPECT(AK::StringUtils::contains(test_string, "BCX", CaseSensitivity::CaseSensitive));
EXPECT(AK::StringUtils::contains(test_string, "BCX", CaseSensitivity::CaseInsensitive));
EXPECT(AK::StringUtils::contains(test_string, "BcX", CaseSensitivity::CaseInsensitive));
EXPECT(!AK::StringUtils::contains(test_string, "xyz", CaseSensitivity::CaseSensitive));
EXPECT(AK::StringUtils::contains(test_string, "xyz", CaseSensitivity::CaseInsensitive));
EXPECT(!AK::StringUtils::contains(test_string, "EFG", CaseSensitivity::CaseSensitive));
EXPECT(!AK::StringUtils::contains(test_string, "EfG", CaseSensitivity::CaseInsensitive));
EXPECT(AK::StringUtils::contains(test_string, "", CaseSensitivity::CaseSensitive));