Add CppUtilities::endsWith()

charconv
Martchus 3 years ago
parent 9a95db3773
commit 1177381521
  1. 33
      conversion/stringconversion.h
  2. 26
      tests/conversiontests.cpp

@ -241,6 +241,39 @@ template <typename StringType> bool startsWith(const StringType &str, const type
return false;
}
/*!
* \brief Returns whether \a str ends with \a phrase.
*/
template <typename StringType> bool endsWith(const StringType &str, const StringType &phrase)
{
if (str.size() < phrase.size()) {
return false;
}
for (auto stri = str.cend() - phrase.size(), strend = str.cend(), phrasei = phrase.cbegin(); stri != strend; ++stri, ++phrasei) {
if (*stri != *phrasei) {
return false;
}
}
return true;
}
/*!
* \brief Returns whether \a str ends with \a phrase.
*/
template <typename StringType> bool endsWith(const StringType &str, const typename StringType::value_type *phrase)
{
const auto phraseSize = std::strlen(phrase);
if (str.size() < phraseSize) {
return false;
}
for (auto stri = str.cend() - phraseSize, strend = str.cend(); stri != strend; ++stri, ++phrase) {
if (*stri != *phrase) {
return false;
}
}
return true;
}
/*!
* \brief Returns whether \a str contains the specified \a substrings.
* \remarks The \a substrings must occur in the specified order.

@ -311,14 +311,24 @@ void ConversionTests::testStringConversions()
CPPUNIT_ASSERT_EQUAL("findOrReplace()"s, findReplaceTest);
// startsWith()
CPPUNIT_ASSERT(!startsWith<string>(findReplaceTest, "findAnd"));
CPPUNIT_ASSERT(startsWith<string>(findReplaceTest, "findOr"));
CPPUNIT_ASSERT(!startsWith<string>(findReplaceTest, "findAnd"s));
CPPUNIT_ASSERT(startsWith<string>(findReplaceTest, "findOr"s));
CPPUNIT_ASSERT(startsWith<string>("test"s, "test"s));
CPPUNIT_ASSERT(startsWith<string>("test"s, "test"));
CPPUNIT_ASSERT(!startsWith<string>("test"s, "tests"s));
CPPUNIT_ASSERT(!startsWith<string>("test"s, "tests"));
CPPUNIT_ASSERT(!startsWith(findReplaceTest, "findAnd"));
CPPUNIT_ASSERT(startsWith(findReplaceTest, "findOr"));
CPPUNIT_ASSERT(!startsWith(findReplaceTest, "findAnd"s));
CPPUNIT_ASSERT(startsWith(findReplaceTest, "findOr"s));
CPPUNIT_ASSERT(startsWith("test"s, "test"s));
CPPUNIT_ASSERT(startsWith("test"s, "test"));
CPPUNIT_ASSERT(!startsWith("test"s, "tests"s));
CPPUNIT_ASSERT(!startsWith("test"s, "tests"));
// endsWith()
CPPUNIT_ASSERT(!endsWith(findReplaceTest, "AndReplace()"));
CPPUNIT_ASSERT(endsWith(findReplaceTest, "OrReplace()"));
CPPUNIT_ASSERT(!endsWith(findReplaceTest, "AndReplace()"s));
CPPUNIT_ASSERT(endsWith(findReplaceTest, "OrReplace()"s));
CPPUNIT_ASSERT(endsWith("test"s, "test"s));
CPPUNIT_ASSERT(endsWith("test"s, "test"));
CPPUNIT_ASSERT(!endsWith("test"s, " test"s));
CPPUNIT_ASSERT(!endsWith("test"s, " test"));
// containsSubstrings()
CPPUNIT_ASSERT(containsSubstrings<string>("this string contains foo and bar", { "foo", "bar" }));

Loading…
Cancel
Save