String+StringView: Add split()
This commit is contained in:
parent
3a28771520
commit
fe348d56c0
@ -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, ...);
|
||||
|
||||
|
@ -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;
|
||||
|
@ -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");
|
||||
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user