return result;
}
+std::vector<std::string> splitDelimitedString(const std::string &str, char delim)
+{
+ std::vector<std::string> result;
+ size_t currPos = 0;
+ const size_t len = str.length();
+ if (len > 0)
+ {
+ size_t nextDelim;
+ do
+ {
+ nextDelim = str.find(delim, currPos);
+ result.push_back(str.substr(currPos, nextDelim - currPos));
+ currPos = nextDelim < len ? nextDelim + 1 : len;
+ }
+ while (currPos < len || nextDelim < len);
+ }
+ return result;
+}
+
namespace
{
* separator.
*/
std::vector<std::string> splitString(const std::string &str);
+/*! \brief
+ * Splits a string to tokens separated by a given delimiter.
+ *
+ * \param[in] str String to process.
+ * \param[in] delim Delimiter to use for splitting.
+ * \returns \p str split into tokens at delimiter.
+ * \throws std::bad_alloc if out of memory.
+ *
+ * Unlike splitString(), consencutive delimiters will generate empty tokens, as
+ * will leading or trailing delimiters.
+ * Empty input will return an empty vector.
+ */
+std::vector<std::string> splitDelimitedString(const std::string &str, char delim);
/*! \brief
* Replace all occurrences of a string with another string.
/*
* This file is part of the GROMACS molecular simulation package.
*
- * Copyright (c) 2012,2014,2015, by the GROMACS development team, led by
+ * Copyright (c) 2012,2014,2015,2016, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
EXPECT_THAT(gmx::splitString(" "), IsEmpty());
}
+TEST(StringUtilityTest, SplitDelimitedString)
+{
+ using ::testing::ElementsAre;
+ using ::testing::IsEmpty;
+ EXPECT_THAT(gmx::splitDelimitedString("foo;bar", ';'), ElementsAre("foo", "bar"));
+ EXPECT_THAT(gmx::splitDelimitedString(";foo;bar;", ';'), ElementsAre("", "foo", "bar", ""));
+ EXPECT_THAT(gmx::splitDelimitedString("foo;;bar", ';'), ElementsAre("foo", "", "bar"));
+ EXPECT_THAT(gmx::splitDelimitedString("foo", ';'), ElementsAre("foo"));
+ EXPECT_THAT(gmx::splitDelimitedString(";", ';'), ElementsAre("", ""));
+ EXPECT_THAT(gmx::splitDelimitedString("", ';'), IsEmpty());
+}
+
/********************************************************************
* Tests for formatString()
*/