Add split(string_view, char) util function

pull/1186/head
Stephen Shelton 4 years ago
parent ffc58fcedb
commit e9708a5d1c
No known key found for this signature in database
GPG Key ID: EE4BADACCE8B631C

@ -78,4 +78,35 @@ namespace llarp
return str;
}
std::vector<string_view>
split(string_view str, char delimiter)
{
std::vector<string_view> splits;
size_t last = 0;
size_t next = 0;
while (last < str.size() and next < string_view::npos)
{
next = str.find_first_of(delimiter, last);
if (next > last)
{
splits.push_back(str.substr(last, next-last));
last = next;
// advance to next non-delimiter
while (str[last] == delimiter)
last++;
}
else
{
break;
}
}
return splits;
}
} // namespace llarp

@ -3,6 +3,7 @@
#include <util/string_view.hpp>
#include <sstream>
#include <vector>
namespace llarp
{
@ -41,6 +42,14 @@ namespace llarp
return o.str();
}
/// Split a string on a given delimiter
//
/// @param str is the string to split
/// @param delimiter is the character to split on
/// @return a vector of string_views with the split words, excluding the delimeter
std::vector<string_view>
split(string_view str, char delimiter);
} // namespace llarp
#endif

@ -1,6 +1,8 @@
#include <util/str.hpp>
#include <catch2/catch.hpp>
#include <vector>
using namespace std::literals;
TEST_CASE("TrimWhitespace -- positive tests", "[str][trim]")
@ -91,3 +93,40 @@ TEST_CASE("neither true nor false string values", "[str][nottruefalse]") {
REQUIRE( !llarp::IsTrueValue(val) );
REQUIRE( !llarp::IsFalseValue(val) );
}
TEST_CASE("split strings with multiple matches", "[str]") {
auto splits = llarp::split("this is a test", ' ');
REQUIRE(splits.size() == 4);
REQUIRE(splits[0] == "this");
REQUIRE(splits[1] == "is");
REQUIRE(splits[2] == "a");
REQUIRE(splits[3] == "test");
}
TEST_CASE("split strings with single match", "[str]") {
auto splits = llarp::split("uno", ';');
REQUIRE(splits.size() == 1);
REQUIRE(splits[0] == "uno");
}
TEST_CASE("split strings with consecutive delimiters", "[str]") {
auto splits = llarp::split("a o e u", ' ');
REQUIRE(splits.size() == 4);
REQUIRE(splits[0] == "a");
REQUIRE(splits[1] == "o");
REQUIRE(splits[2] == "e");
REQUIRE(splits[3] == "u");
}
TEST_CASE("split delimiter-only string", "[str]") {
auto splits = llarp::split(" ", ' ');
REQUIRE(splits.size() == 0);
splits = llarp::split(" ", ' ');
REQUIRE(splits.size() == 0);
}
TEST_CASE("split empty string", "[str]") {
auto splits = llarp::split("", ' ');
REQUIRE(splits.size() == 0);
}

Loading…
Cancel
Save