String+StringView: Add split()

This commit is contained in:
apio 2023-04-07 15:14:46 +02:00
parent 3a28771520
commit fe348d56c0
Signed by: apio
GPG Key ID: B8A7D06E42258954
4 changed files with 37 additions and 0 deletions

View File

@ -26,6 +26,8 @@ class String
Result<String> substring(usize begin, usize size) const;
Result<Vector<String>> split(StringView delim) const;
static Result<String> format(const String& fmt, ...);
static Result<String> format(StringView fmt, ...);

View File

@ -1,5 +1,6 @@
#pragma once
#include <luna/Result.h>
#include <luna/Vector.h>
class String;
@ -37,6 +38,8 @@ class StringView
bool operator==(const char* other) const;
bool operator==(StringView other) const;
Result<Vector<String>> split(StringView delim) const;
Iterator begin() const
{
return m_string;

View File

@ -75,6 +75,11 @@ Result<String> String::substring(usize begin, usize size) const
return String { dup, size };
}
Result<Vector<String>> String::split(StringView delim) const
{
return view().split(delim);
}
const char& String::operator[](usize index) const
{
expect(index < m_length, "index out of range");

View File

@ -46,6 +46,33 @@ bool StringView::operator==(StringView other) const
return !strcmp(m_string, other.m_string);
}
Result<Vector<String>> StringView::split(StringView delim) const
{
Vector<String> result;
String str;
char* copy = strndup(m_string, m_length);
char* segment = strtok(copy, delim.chars());
if (!segment) goto end;
str = TRY(String::from_cstring(segment));
TRY(result.try_append(move(str)));
while (true)
{
segment = strtok(nullptr, delim.chars());
if (!segment) goto end;
str = TRY(String::from_cstring(segment));
TRY(result.try_append(move(str)));
}
end:
free_impl(copy);
return result;
}
Result<String> StringView::to_string()
{
return String::from_cstring(m_string);