Fix startsWith() if strings are equal

This commit is contained in:
Martchus 2019-10-27 15:43:44 +01:00
parent a841d764d5
commit 2cdde81077
2 changed files with 10 additions and 2 deletions

View File

@ -212,9 +212,11 @@ template <typename StringType> bool startsWith(const StringType &str, const Stri
if (str.size() < phrase.size()) { if (str.size() < phrase.size()) {
return false; return false;
} }
for (auto stri = str.cbegin(), strend = str.cend(), phrasei = phrase.cbegin(), phraseend = phrase.cend(); stri != strend; ++stri, ++phrasei) { for (auto stri = str.cbegin(), strend = str.cend(), phrasei = phrase.cbegin(), phraseend = phrase.cend();; ++stri, ++phrasei) {
if (phrasei == phraseend) { if (phrasei == phraseend) {
return true; return true;
} else if (stri == strend) {
return false;
} else if (*stri != *phrasei) { } else if (*stri != *phrasei) {
return false; return false;
} }
@ -227,9 +229,11 @@ template <typename StringType> bool startsWith(const StringType &str, const Stri
*/ */
template <typename StringType> bool startsWith(const StringType &str, const typename StringType::value_type *phrase) template <typename StringType> bool startsWith(const StringType &str, const typename StringType::value_type *phrase)
{ {
for (auto stri = str.cbegin(), strend = str.cend(); stri != strend; ++stri, ++phrase) { for (auto stri = str.cbegin(), strend = str.cend();; ++stri, ++phrase) {
if (!*phrase) { if (!*phrase) {
return true; return true;
} else if (stri == strend) {
return false;
} else if (*stri != *phrase) { } else if (*stri != *phrase) {
return false; return false;
} }

View File

@ -315,6 +315,10 @@ void ConversionTests::testStringConversions()
CPPUNIT_ASSERT(startsWith<string>(findReplaceTest, "findOr")); CPPUNIT_ASSERT(startsWith<string>(findReplaceTest, "findOr"));
CPPUNIT_ASSERT(!startsWith<string>(findReplaceTest, "findAnd"s)); CPPUNIT_ASSERT(!startsWith<string>(findReplaceTest, "findAnd"s));
CPPUNIT_ASSERT(startsWith<string>(findReplaceTest, "findOr"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"));
// containsSubstrings() // containsSubstrings()
CPPUNIT_ASSERT(containsSubstrings<string>("this string contains foo and bar", { "foo", "bar" })); CPPUNIT_ASSERT(containsSubstrings<string>("this string contains foo and bar", { "foo", "bar" }));