diff --git a/lib/Support/StringRef.cpp b/lib/Support/StringRef.cpp index 4bafc4ec718..d7fa99dbde2 100644 --- a/lib/Support/StringRef.cpp +++ b/lib/Support/StringRef.cpp @@ -374,9 +374,14 @@ size_t StringRef::count(StringRef Str) const { size_t N = Str.size(); if (N > Length) return 0; - for (size_t i = 0, e = Length - N + 1; i != e; ++i) - if (substr(i, N).equals(Str)) + for (size_t i = 0, e = Length - N + 1; i < e;) { + if (substr(i, N).equals(Str)) { ++Count; + i += N; + } + else + ++i; + } return Count; } diff --git a/unittests/ADT/StringRefTest.cpp b/unittests/ADT/StringRefTest.cpp index 2e5159dde1c..cbb2a30ff17 100644 --- a/unittests/ADT/StringRefTest.cpp +++ b/unittests/ADT/StringRefTest.cpp @@ -509,6 +509,13 @@ TEST(StringRefTest, Count) { EXPECT_EQ(1U, Str.count("hello")); EXPECT_EQ(1U, Str.count("ello")); EXPECT_EQ(0U, Str.count("zz")); + + StringRef OverlappingAbba("abbabba"); + EXPECT_EQ(1U, OverlappingAbba.count("abba")); + StringRef NonOverlappingAbba("abbaabba"); + EXPECT_EQ(2U, NonOverlappingAbba.count("abba")); + StringRef ComplexAbba("abbabbaxyzabbaxyz"); + EXPECT_EQ(2U, ComplexAbba.count("abba")); } TEST(StringRefTest, EditDistance) {