add utility function to compare two string while ignoring whitespace

This commit is contained in:
Axel Kohlmeyer
2025-01-17 14:06:30 -05:00
parent 90416b63fc
commit 9b443c9a4d
4 changed files with 50 additions and 0 deletions

View File

@ -166,6 +166,9 @@ and parsing files or arguments.
.. doxygenfunction:: split_lines .. doxygenfunction:: split_lines
:project: progguide :project: progguide
.. doxygenfunction:: strsame
:project: progguide
.. doxygenfunction:: strmatch .. doxygenfunction:: strmatch
:project: progguide :project: progguide

View File

@ -111,6 +111,29 @@ bool utils::strmatch(const std::string &text, const std::string &pattern)
return (pos >= 0); return (pos >= 0);
} }
bool utils::strsame(const std::string &text1, const std::string &text2)
{
const char *ptr1 = text1.c_str();
const char *ptr2 = text2.c_str();
while (*ptr1 && *ptr2) {
// ignore whitespace
while (*ptr1 && isblank(*ptr1)) ++ptr1;
while (*ptr2 && isblank(*ptr2)) ++ptr2;
// strings differ
if (*ptr1 != *ptr2) return false;
// reached end of both strings
if (!*ptr1 && !*ptr2) return true;
++ptr1;
++ptr2;
}
return true;
}
/** This function is a companion function to utils::strmatch(). Arguments /** This function is a companion function to utils::strmatch(). Arguments
* and logic is the same, but instead of a boolean, it returns the * and logic is the same, but instead of a boolean, it returns the
* sub-string that matches the regex pattern. There can be only one match. * sub-string that matches the regex pattern. There can be only one match.

View File

@ -41,6 +41,14 @@ namespace utils {
bool strmatch(const std::string &text, const std::string &pattern); bool strmatch(const std::string &text, const std::string &pattern);
/*! Compare two string while ignoring whitespace
*
* \param text1 the first text to be compared
* \param text2 the second text to be compared
* \return true if the non-whitespace part of the two strings matches, false if not */
bool strsame(const std::string &text1, const std::string &text2);
/*! Find sub-string that matches a simplified regex pattern /*! Find sub-string that matches a simplified regex pattern
* *
* \param text the text to be matched against the pattern * \param text the text to be matched against the pattern

View File

@ -46,6 +46,22 @@ TEST(Utils, strdup)
delete[] copy2; delete[] copy2;
} }
TEST(Utils, strsame)
{
std::string text1("some_text");
std::string text2("some_text");
ASSERT_TRUE(utils::strsame(text1,text2));
text1 = " some _\ttext\n ";
ASSERT_TRUE(utils::strsame(text1,text2));
text2 = " some _ text\n ";
ASSERT_TRUE(utils::strsame(text1,text2));
text2 = "some_other_text";
ASSERT_FALSE(utils::strsame(text1,text2));
text2 = " some other_text";
ASSERT_FALSE(utils::strsame(text1,text2));
}
TEST(Utils, trim) TEST(Utils, trim)
{ {
auto trimmed = utils::trim("\t some text"); auto trimmed = utils::trim("\t some text");