diff --git a/src/utils.cpp b/src/utils.cpp index 4efa35a8d1..ce6a64f22f 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -348,6 +348,19 @@ tagint utils::tnumeric(const char *file, int line, const char *str, return ATOTAGINT(str); } +/* ---------------------------------------------------------------------- + Return string without leading or trailing whitespace +------------------------------------------------------------------------- */ + +std::string utils::trim(const std::string & line) { + int beg = re_match(line.c_str(),"\\S+"); + int end = re_match(line.c_str(),"\\s+$"); + if (beg < 0) beg = 0; + if (end < 0) end = line.size(); + + return line.substr(beg,end-beg); +} + /* ---------------------------------------------------------------------- Return string without trailing # comment ------------------------------------------------------------------------- */ diff --git a/src/utils.h b/src/utils.h index abaa87ca5f..3919f8d4d5 100644 --- a/src/utils.h +++ b/src/utils.h @@ -143,6 +143,13 @@ namespace LAMMPS_NS { tagint tnumeric(const char *file, int line, const char *str, bool do_abort, LAMMPS *lmp); + /** + * \brief Trim leading and trailing whitespace. Like TRIM() in Fortran. + * \param line string that should be trimmed + * \return new string without whitespace (string) + */ + std::string trim(const std::string &line); + /** * \brief Trim anything from '#' onward * \param line string that should be trimmed diff --git a/unittest/utils/test_utils.cpp b/unittest/utils/test_utils.cpp index 22a647f460..08aa5df1ff 100644 --- a/unittest/utils/test_utils.cpp +++ b/unittest/utils/test_utils.cpp @@ -25,6 +25,24 @@ using ::testing::EndsWith; using ::testing::Eq; using ::testing::StrEq; +TEST(Utils, trim) +{ + auto trimmed = utils::trim("\t some text"); + ASSERT_THAT(trimmed, StrEq("some text")); + + trimmed = utils::trim("some text \r\n"); + ASSERT_THAT(trimmed, StrEq("some text")); + + trimmed = utils::trim("\v some text \f"); + ASSERT_THAT(trimmed, StrEq("some text")); + + trimmed = utils::trim(" some\t text "); + ASSERT_THAT(trimmed, StrEq("some\t text")); + + trimmed = utils::trim(" \t\n "); + ASSERT_THAT(trimmed, StrEq("")); +} + TEST(Utils, trim_comment) { auto trimmed = utils::trim_comment("some text # comment");