Skip to content

Commit

Permalink
Add CStringArray::join() method
Browse files Browse the repository at this point in the history
  • Loading branch information
mikee47 committed Sep 23, 2023
1 parent 1d4f0cc commit d2624ad
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Sming/Core/Data/CStringArray.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,25 @@ unsigned CStringArray::count() const
}
return stringCount;
}

String CStringArray::join(const String& separator) const
{
if(isNull()) {
return nullptr;
}
unsigned len = length();
if(len == 0) {
return "";
}
len -= count(); // NUL separators
len += separator.length() * (stringCount - 1);
String s;
s.reserve(len);
for(auto it = begin(); it != end(); ++it) {
if(it.index() != 0) {
s += separator;
}
s += *it;
}
return s;
}
9 changes: 9 additions & 0 deletions Sming/Core/Data/CStringArray.h
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,15 @@ class CStringArray : private String
*/
unsigned count() const;

/**
* @brief Get contents of array as delimited string
* @param separator What to join elements with
* @retval String
*
* e.g. CStringArray(F("a\0b\0c")).join() returns "a,b,c"
*/
String join(const String& separator = ",") const;

/**
* @name Iterator support (forward only)
* @{
Expand Down
19 changes: 19 additions & 0 deletions tests/HostTests/modules/CStringArray.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,25 @@ class CStringArrayTest : public TestGroup
REQUIRE(csa.back() == nullptr);
REQUIRE(!csa.popBack());
}

TEST_CASE("join")
{
CStringArray csa;
REQUIRE(!csa.join());

csa = "";
REQUIRE(csa.join() == "");

csa.add("a");
REQUIRE(csa.join() == "a");

csa.add("");
REQUIRE(csa.join() == "a,");

csa.add(F("test\0again"));
REQUIRE_EQ(csa.join("}+{"), "a}+{}+{test}+{again");
REQUIRE_EQ(csa.join(nullptr), "atestagain");
}
}
};

Expand Down

0 comments on commit d2624ad

Please sign in to comment.