libluna: Add String::join()

This commit is contained in:
apio 2023-05-01 19:29:17 +02:00
parent 7fbc644753
commit df590f4e26
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 20 additions and 0 deletions

View File

@ -32,6 +32,8 @@ class String
return view().split_once(delim);
}
static Result<String> join(const Vector<String>& vec, StringView delim);
void trim(StringView delim);
static Result<String> format(const String& fmt, ...);

View File

@ -2,6 +2,7 @@
#include <luna/CString.h>
#include <luna/Format.h>
#include <luna/String.h>
#include <luna/StringBuilder.h>
#include <luna/Vector.h>
String::String()
@ -163,3 +164,20 @@ Result<String> String::from_cstring(const char* str)
if (!dup) return err(ENOMEM);
return String { dup };
}
Result<String> String::join(const Vector<String>& vec, StringView delim)
{
if (vec.size() == 0) return String {};
if (vec.size() == 1) return vec[0].clone();
StringBuilder sb;
TRY(sb.add(vec[0].view()));
for (usize i = 1; i < vec.size(); i++)
{
TRY(sb.add(delim));
TRY(sb.add(vec[i].view()));
}
return sb.string();
}