From faf2f9920e0beca479feb3192e9b6b3d8bf85d72 Mon Sep 17 00:00:00 2001 From: joe-conigliaro Date: Sat, 3 Aug 2019 07:30:22 +1000 Subject: [PATCH] string.v: string.count(substr) --- vlib/builtin/string.v | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 45443bce76..6670e5c888 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -454,6 +454,22 @@ pub fn (s string) index_after(p string, start int) int { return -1 } +// counts occurrences of substr in s +pub fn (s string) count(substr string) int { + if s.len == 0 || substr.len == 0 { + return 0 + } + mut n := 0 + for { + i := s.index(substr) + if i == -1 { + return n + } + n++ + s = s.right(i+substr.len) + } +} + pub fn (s string) contains(p string) bool { res := s.index(p) > 0 - 1 return res