1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 04:28:13 +00:00

AK: Add StringView::find_first/last_of

These methods search from the beginning or end of a string for the
first character in the input StringView and returns the position in
the string of the first match. Note that this is not a substring match.
Each comes with single char overloads for efficiency.
This commit is contained in:
Andrew Kaster 2020-05-02 12:21:20 -06:00 committed by Andreas Kling
parent 94c28552c6
commit 3eb3c2477f
3 changed files with 91 additions and 0 deletions

View file

@ -222,4 +222,46 @@ bool StringView::operator==(const String& string) const
return !__builtin_memcmp(m_characters, string.characters(), m_length);
}
Optional<size_t> StringView::find_first_of(char c) const
{
for (size_t pos = 0; pos < m_length; ++pos) {
if (m_characters[pos] == c)
return pos;
}
return {};
}
Optional<size_t> StringView::find_first_of(const StringView& view) const
{
for (size_t pos = 0; pos < m_length; ++pos) {
char c = m_characters[pos];
for (char view_char : view) {
if (c == view_char)
return pos;
}
}
return {};
}
Optional<size_t> StringView::find_last_of(char c) const
{
for (size_t pos = m_length; --pos >0;) {
if (m_characters[pos] == c)
return pos;
}
return {};
}
Optional<size_t> StringView::find_last_of(const StringView& view) const
{
for (size_t pos = m_length - 1; --pos > 0;) {
char c = m_characters[pos];
for (char view_char : view) {
if (c == view_char)
return pos;
}
}
return {};
}
}