diff --git a/libluna/include/luna/String.h b/libluna/include/luna/String.h index b9832d2a..f477e883 100644 --- a/libluna/include/luna/String.h +++ b/libluna/include/luna/String.h @@ -55,6 +55,9 @@ class String /* Creates a single String consisting of a list of strings separated by a delimiter. */ static Result join(const Vector& vec, StringView delim); + /* Creates a single String consisting of a list of strings separated by a delimiter. */ + static Result join(const Vector& vec, StringView delim); + /* Removes all trailing characters contained in delim. */ void trim(StringView delim); diff --git a/libluna/src/String.cpp b/libluna/src/String.cpp index 81a4c48e..317e0578 100644 --- a/libluna/src/String.cpp +++ b/libluna/src/String.cpp @@ -181,6 +181,23 @@ Result String::join(const Vector& vec, StringView delim) return sb.string(); } +Result String::join(const Vector& vec, StringView delim) +{ + if (vec.size() == 0) return String {}; + if (vec.size() == 1) return from_string_view(vec[0]); + + StringBuilder sb; + TRY(sb.add(vec[0])); + + for (usize i = 1; i < vec.size(); i++) + { + TRY(sb.add(delim)); + TRY(sb.add(vec[i])); + } + + return sb.string(); +} + int String::compare(const String* a, const String* b) { return strcmp(a->chars(), b->chars());