Add CppUtilities::endsWith()

This commit is contained in:
Martchus 2019-10-30 20:34:16 +01:00
parent 9a95db3773
commit 1177381521
2 changed files with 51 additions and 8 deletions

View File

@ -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.

View File

@ -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" }));