Add optimized version of count_words for default whitespace chars

This commit is contained in:
Richard Berger
2020-06-11 13:37:22 -04:00
parent 9945f73743
commit 6cb5345cd0
3 changed files with 42 additions and 1 deletions

View File

@ -368,6 +368,35 @@ std::string utils::trim_comment(const std::string & line) {
Return number of words 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 utils::count_words(const std::string & text, const std::string & separators) {
size_t count = 0; size_t count = 0;
size_t start = text.find_first_not_of(separators); size_t start = text.find_first_not_of(separators);

View File

@ -156,7 +156,15 @@ namespace LAMMPS_NS {
* \param separators string containing characters that will be treated as whitespace * \param separators string containing characters that will be treated as whitespace
* \return number of words found * \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 * \brief Count words in a single line, trim anything from '#' onward

View File

@ -28,6 +28,10 @@ TEST(Utils, count_words) {
ASSERT_EQ(utils::count_words("some text # comment"), 4); 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) { TEST(Utils, trim_and_count_words) {
ASSERT_EQ(utils::trim_and_count_words("some text # comment"), 2); ASSERT_EQ(utils::trim_and_count_words("some text # comment"), 2);
} }