Add StringRef::count({char,StringRef})
authorDaniel Dunbar <daniel@zuster.org>
Tue, 18 Aug 2009 18:26:35 +0000 (18:26 +0000)
committerDaniel Dunbar <daniel@zuster.org>
Tue, 18 Aug 2009 18:26:35 +0000 (18:26 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@79354 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/ADT/StringRef.h
unittests/ADT/StringRefTest.cpp

index 40689a98870a186b742516a1b9ee167928ef3caf..5433056039065f339e5c90b4f8193fad58140ac1 100644 (file)
@@ -172,6 +172,28 @@ namespace llvm {
       return npos;
     }
 
+    /// count - Return the number of occurrences of \arg C in the string.
+    size_t count(char C) const {
+      size_t Count = 0;
+      for (size_t i = 0, e = Length; i != e; ++i)
+        if (Data[i] == C)
+          return i;
+      return Count;
+    }
+
+    /// count - Return the number of non-overlapped occurrences of \arg Str in
+    /// the string.
+    size_t count(const StringRef &Str) const {
+      size_t Count = 0;
+      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))
+          ++Count;
+      return Count;
+    }
+
     /// @}
     /// @name Substring Operations
     /// @{
index 972201c1ff0751d829b277bd94681956ac2e9749..ef89e9f3f9d990a12303f270117effd7add5ff9c 100644 (file)
@@ -94,6 +94,13 @@ TEST(StringRefTest, Utilities) {
   EXPECT_TRUE(Str.find("hello") == 0);
   EXPECT_TRUE(Str.find("ello") == 1);
   EXPECT_TRUE(Str.find("zz") == StringRef::npos);
+
+  EXPECT_TRUE(Str.count('l') == 2);
+  EXPECT_TRUE(Str.count('z') == 0);
+  EXPECT_TRUE(Str.count("helloworld") == 0);
+  EXPECT_TRUE(Str.count("hello") == 1);
+  EXPECT_TRUE(Str.count("ello") == 1);
+  EXPECT_TRUE(Str.count("zz") == 0);
 }
 
 } // end anonymous namespace