From: James Turner Date: Thu, 20 Oct 2011 10:12:54 +0000 (+0100) Subject: string list joining, and a test case for that and splitting. X-Git-Url: https://git.mxchange.org/?a=commitdiff_plain;h=7984f055e26162798812c94a0cc49dd73cd6bea8;p=simgear.git string list joining, and a test case for that and splitting. --- diff --git a/simgear/misc/strutils.cxx b/simgear/misc/strutils.cxx index 5a669a6b..b1f74318 100644 --- a/simgear/misc/strutils.cxx +++ b/simgear/misc/strutils.cxx @@ -278,6 +278,19 @@ namespace simgear { return v1parts.size() - v2parts.size(); } + string join(const string_list& l, const string& joinWith) + { + string result; + unsigned int count = l.size(); + for (unsigned int i=0; i < count; ++i) { + result += l[i]; + if (i < (count - 1)) { + result += joinWith; + } + } + + return result; + } } // end namespace strutils diff --git a/simgear/misc/strutils.hxx b/simgear/misc/strutils.hxx index 091ba823..9bd1dbe1 100644 --- a/simgear/misc/strutils.hxx +++ b/simgear/misc/strutils.hxx @@ -33,6 +33,7 @@ #include #include +typedef std::vector < std::string > string_list; namespace simgear { namespace strutils { @@ -93,11 +94,17 @@ namespace simgear { * resulting in at most maxsplit+1 words. * @return Array of words. */ - std::vector + string_list split( const std::string& s, const char* sep = 0, int maxsplit = 0 ); + /** + * create a single string by joining the elements of a list with + * another string. + */ + std::string join(const string_list& l, const std::string& joinWith = ""); + /** * Test if a string starts with a string * diff --git a/simgear/misc/strutils_test.cxx b/simgear/misc/strutils_test.cxx index 8369f4ea..6387b47c 100644 --- a/simgear/misc/strutils_test.cxx +++ b/simgear/misc/strutils_test.cxx @@ -63,6 +63,20 @@ int main (int ac, char ** av) // since we compare numerically, leasing zeros shouldn't matter VERIFY(compare_versions("0.06.7", "0.6.07") == 0); + string_list la = split("zero one two three four five"); + COMPARE(la[2], "two"); + COMPARE(la[5], "five"); + COMPARE(la.size(), 6); + + string_list lb = split("alpha:beta:gamma:delta", ":", 2); + COMPARE(lb.size(), 3); + COMPARE(lb[0], "alpha"); + COMPARE(lb[1], "beta"); + COMPARE(lb[2], "gamma:delta"); + + std::string j = join(la, "&"); + COMPARE(j, "zero&one&two&three&four&five"); + cout << "all tests passed successfully!" << endl; return 0; }