Unverified Commit 6cb5345c authored by Richard Berger's avatar Richard Berger
Browse files

Add optimized version of count_words for default whitespace chars

parent 9945f737
Loading
Loading
Loading
Loading
+29 −0
Original line number Diff line number Diff line
@@ -368,6 +368,35 @@ std::string utils::trim_comment(const std::string & line) {
   Return number of words
------------------------------------------------------------------------- */

size_t utils::count_words(const std::string & text) {
  size_t count = 0;
  const char * buf = text.c_str();
  char c = *buf;

  while (c) {
    if (c == ' ' || c == '\t' || c == '\r' ||  c == '\n' || c == '\f') {
      c = *++buf;
      continue;
    };

    ++count;
    c = *++buf;

    while (c) {
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f') {
        break;
      }
      c = *++buf;
    }
  }

  return count;
}

/* ----------------------------------------------------------------------
   Return number of words
------------------------------------------------------------------------- */

size_t utils::count_words(const std::string & text, const std::string & separators) {
  size_t count = 0;
  size_t start = text.find_first_not_of(separators);
+9 −1
Original line number Diff line number Diff line
@@ -156,7 +156,15 @@ namespace LAMMPS_NS {
     * \param separators string containing characters that will be treated as whitespace
     * \return number of words found
     */
    size_t count_words(const std::string & text, const std::string & separators = " \t\r\n\f");
    size_t count_words(const std::string & text, const std::string & separators);

    /**
     * \brief Count words in string, ignore any whitespace matching " \t\r\n\f"
     * \param text string that should be searched
     * \param separators string containing characters that will be treated as whitespace
     * \return number of words found
     */
    size_t count_words(const std::string & text);

    /**
     * \brief Count words in a single line, trim anything from '#' onward
+4 −0
Original line number Diff line number Diff line
@@ -28,6 +28,10 @@ TEST(Utils, count_words) {
    ASSERT_EQ(utils::count_words("some text # comment"), 4);
}

TEST(Utils, count_words_non_default) {
    ASSERT_EQ(utils::count_words("some text # comment", " #"), 3);
}

TEST(Utils, trim_and_count_words) {
    ASSERT_EQ(utils::trim_and_count_words("some text # comment"), 2);
}