1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 08:54:58 +00:00

AK: Reimplement StringView::find methods in StringUtils

This patch reimplements the StringView::find methods in StringUtils, so
they can also be used by String. The methods now also take an optional
start parameter, which moves their API in line with String's respective
methods.

This also implements a StringView::find_ast(char) method, which is
currently functionally equivalent to find_last_of(char). This is because
find_last_of(char) will be removed in a further commit.
This commit is contained in:
Max Wipfli 2021-07-01 14:58:37 +02:00 committed by Andreas Kling
parent 3ea65200d8
commit 56253bf389
5 changed files with 37 additions and 20 deletions

View file

@ -332,11 +332,34 @@ StringView trim_whitespace(const StringView& str, TrimMode mode)
return trim(str, " \n\t\v\f\r", mode);
}
Optional<size_t> find(const StringView& haystack, const StringView& needle)
Optional<size_t> find(StringView const& haystack, char needle, size_t start)
{
return AK::memmem_optional(
haystack.characters_without_null_termination(), haystack.length(),
if (start >= haystack.length())
return {};
for (size_t i = start; i < haystack.length(); ++i) {
if (haystack[i] == needle)
return i;
}
return {};
}
Optional<size_t> find(StringView const& haystack, StringView const& needle, size_t start)
{
if (start > haystack.length())
return {};
auto index = AK::memmem_optional(
haystack.characters_without_null_termination() + start, haystack.length() - start,
needle.characters_without_null_termination(), needle.length());
return index.has_value() ? (*index + start) : index;
}
Optional<size_t> find_last(StringView const& haystack, char needle)
{
for (size_t i = haystack.length(); i > 0; --i) {
if (haystack[i - 1] == needle)
return i - 1;
}
return {};
}
String to_snakecase(const StringView& str)