From 4d88f7cb7516eaff402d26efbe635da44a3f0bdb Mon Sep 17 00:00:00 2001 From: ADAM David Alan Martin Date: Sun, 29 Oct 2023 05:57:11 -0400 Subject: [PATCH] Multi-char delimiter string splitting. --- string_algorithms.cpp | 15 +++++++++++++++ string_algorithms.h | 2 ++ string_algorithms.test/0.cc | 20 +++++++++++++++++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/string_algorithms.cpp b/string_algorithms.cpp index 9cc3840..fb69e01 100644 --- a/string_algorithms.cpp +++ b/string_algorithms.cpp @@ -151,4 +151,19 @@ namespace Alepha::Hydrogen ::detail:: string_algorithms rv.push_back( std::move( next ) ); return rv; } + + std::vector< std::string > + exports::split( std::string s, const std::string &delim ) + { + std::vector< std::string > rv; + while( true ) + { + const auto pos= s.find( delim ); + rv.push_back( s.substr( 0, pos ) ); + if( pos == std::string::npos ) break; + s= s.substr( pos + delim.size() ); + } + + return rv; + } } diff --git a/string_algorithms.h b/string_algorithms.h index ff394d0..1039c6f 100644 --- a/string_algorithms.h +++ b/string_algorithms.h @@ -75,6 +75,8 @@ namespace Alepha::Hydrogen ::detail:: string_algorithms std::vector< std::string > split( const std::string &s, char token ); + std::vector< std::string > split( std::string s, const std::string &delim ); + /*! * Parses an integral range description into a vector of values. */ diff --git a/string_algorithms.test/0.cc b/string_algorithms.test/0.cc index ba13f4e..93ec0f4 100644 --- a/string_algorithms.test/0.cc +++ b/string_algorithms.test/0.cc @@ -50,11 +50,29 @@ static auto init= enroll <=[] }, }; - "Does the `split` function handle simple cases correctly?"_test <=TableTest< Alepha::split >::Cases + "Does the `split` function handle simple cases correctly?"_test <=TableTest + < + [] ( const std::string text, const char delim ) { return Alepha::split( text, delim ); } + > + ::Cases { { "Empty string", { "", ':' }, { "" } }, { "Single token", { "item", ':' }, { "item" } }, { "Two tokens", { "first:second", ':' }, { "first", "second" } }, { "Empty string many tokens", { ":::", ':' }, { "", "", "", "" } }, }; + + "Does the `split` function over multi-token-delimiters handle simple cases correctly?"_test <=TableTest + < + [] ( const std::string text, const std::string delim ) { return Alepha::split( text, delim ); } + > + ::Cases + { + { "Empty string", { "", "::" }, { "" } }, + { "Single token", { "item", "::" }, { "item" } }, + { "Two tokens", { "first::second", "::" }, { "first", "second" } }, + { "Empty string many tokens", { "::::::", "::" }, { "", "", "", "" } }, + { "Alphabet string many tokens", { "a::b::c::d", "::" }, { "a", "b", "c", "d" } }, + { "Alphabet string many tokens", { "::a::b::c::d::", "::" }, { "", "a", "b", "c", "d", "" } }, + }; };