diff --git a/conversion/stringconversion.h b/conversion/stringconversion.h index b9e4a6e..65659cd 100644 --- a/conversion/stringconversion.h +++ b/conversion/stringconversion.h @@ -241,6 +241,39 @@ template bool startsWith(const StringType &str, const type return false; } +/*! + * \brief Returns whether \a str ends with \a phrase. + */ +template 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 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. diff --git a/tests/conversiontests.cpp b/tests/conversiontests.cpp index 0a33b74..6aa8a23 100644 --- a/tests/conversiontests.cpp +++ b/tests/conversiontests.cpp @@ -311,14 +311,24 @@ void ConversionTests::testStringConversions() CPPUNIT_ASSERT_EQUAL("findOrReplace()"s, findReplaceTest); // startsWith() - 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")); + 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("this string contains foo and bar", { "foo", "bar" }));