chrberger / stringtoolbox

A simple header-only, single-file string toolbox library for C++.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The split is still not what I expect

olbender opened this issue · comments

The following should be true:
split("a", '&') == ["a"]
split("a&b", '&') == ["a", "b"]
split("a&", '&') == ["a", ""]
split("&a", '&') == ["", "a"]
split("&", '&') == ["", ""]
split("&&", '&') == ["", "", ""]

I think the world is waiting eagerly for this fix.... ;) Every time I use the split I end up with unexpected results. Now I did
split("111:1", ','); and got []
I have a hacked version that I use here and there, should I fork?

Please have a look at this spec:

https://github.com/chrberger/stringtoolbox/blob/master/test/Test-stringtoolbox.cpp#L103-L139

What cases are in conflict with your desired behaviour?

And as always: we are eagerly accepting your PRs :-)

Current version:

split("a", '&'); ->
split("a&b", '&'); ->
  0: 'a'
  1: 'b'
split("a&", '&'); ->
  0: 'a'
  1: ''
split("&a", '&'); ->
  0: ''
  1: 'a'
split("&", '&'); ->
  0: ''
  1: ''
split("&&", '&'); ->
  0: ''
  1: ''
  2: ''

It's the first that is not what is expected, a single element of "a" should be returned.

Patch:

diff a/stringtoolbox.hpp b/stringtoolbox.hpp
index dfdeb81..d0b1fb0 100644
--- a/stringtoolbox.hpp
+++ b/stringtoolbox.hpp
@@ -82,7 +82,7 @@ inline std::vector<std::string> split(const std::string &str,
       retVal.emplace_back("");
     }
   }
-  if ((prev > 0) && (prev < str.size())) {
+  if (prev < str.size()) {
     retVal.emplace_back(str.substr(prev, str.size() - prev));
   }
   else if (prev > 0) {
diff a/test/Test-stringtoolbox.cpp b/test/Test-stringtoolbox.cpp
index 58c82ef..d22937a 100644
--- a/test/Test-stringtoolbox.cpp
+++ b/test/Test-stringtoolbox.cpp
@@ -103,11 +103,11 @@ TEST_CASE("Test replace all") {
 TEST_CASE("Test split") {
     std::string s1 = "abc";
     std::vector<std::string> vs1 = stringtoolbox::split(s1, ',');
-    REQUIRE(vs1.size() == 0);
+    REQUIRE(vs1.size() == 1);
 
     std::string s2 = "abc;def";
     std::vector<std::string> vs2_no = stringtoolbox::split(s2, ',');
-    REQUIRE(vs2_no.size() == 0);
+    REQUIRE(vs2_no.size() == 1);
     std::vector<std::string> vs2 = stringtoolbox::split(s2, ';');
     REQUIRE(vs2.size() == 2);
     REQUIRE(vs2.at(0) == "abc");