diff options
| author | Sobeston <15335529+Sobeston@users.noreply.github.com> | 2020-08-24 16:47:44 +0100 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2020-08-26 17:37:05 -0400 |
| commit | 7d0bb0774e957e81fee7240d410944a0a56c303d (patch) | |
| tree | eafc09d9d2670498058901ab321a84781afbae18 /lib | |
| parent | 091d693c5381a17d1de01ab372481f629b560c7c (diff) | |
| download | zig-7d0bb0774e957e81fee7240d410944a0a56c303d.tar.gz zig-7d0bb0774e957e81fee7240d410944a0a56c303d.zip | |
std.mem.count
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/std/mem.zig | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 0deb178548..e5c53bbb07 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -893,6 +893,35 @@ test "mem.indexOf" { testing.expect(lastIndexOfScalar(u8, "boo", 'o').? == 2); } +/// Returns the number of needles inside the haystack +/// needle.len must be > 0 +/// does not count overlapping needles +pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize { + assert(needle.len > 0); + var i: usize = 0; + var found: usize = 0; + + while (indexOfPos(T, haystack, i, needle)) |idx| { + i = idx + needle.len; + found += 1; + } + + return found; +} + +test "mem.count" { + testing.expect(count(u8, "", "h") == 0); + testing.expect(count(u8, "h", "h") == 1); + testing.expect(count(u8, "hh", "h") == 2); + testing.expect(count(u8, "world!", "hello") == 0); + testing.expect(count(u8, "hello world!", "hello") == 1); + testing.expect(count(u8, " abcabc abc", "abc") == 3); + testing.expect(count(u8, "udexdcbvbruhasdrw", "bruh") == 1); + testing.expect(count(u8, "foo bar", "o bar") == 1); + testing.expect(count(u8, "foofoofoo", "foo") == 3); + testing.expect(count(u8, "fffffff", "ff") == 3); +} + /// Reads an integer from memory with size equal to bytes.len. /// T specifies the return type, which must be large enough to store /// the result. |
