authorgravatar for 15335529+Sobeston@users.noreply.github.comSobeston <15335529+Sobeston@users.noreply.github.com> 2020-08-24 16:47:44+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-08-26 17:37:05-04:00
log7d0bb0774e957e81fee7240d410944a0a56c303d
treeeafc09d9d2670498058901ab321a84781afbae18
parent091d693c5381a17d1de01ab372481f629b560c7c

std.mem.count


1 files changed, 29 insertions(+), 0 deletions(-)

lib/std/mem.zig+29
...@@ -893,6 +893,35 @@ test "mem.indexOf" {...@@ -893,6 +893,35 @@ test "mem.indexOf" {
893 testing.expect(lastIndexOfScalar(u8, "boo", 'o').? == 2);893 testing.expect(lastIndexOfScalar(u8, "boo", 'o').? == 2);
894}894}
895895
896/// Returns the number of needles inside the haystack
897/// needle.len must be > 0
898/// does not count overlapping needles
899pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize {
900 assert(needle.len > 0);
901 var i: usize = 0;
902 var found: usize = 0;
903
904 while (indexOfPos(T, haystack, i, needle)) |idx| {
905 i = idx + needle.len;
906 found += 1;
907 }
908
909 return found;
910}
911
912test "mem.count" {
913 testing.expect(count(u8, "", "h") == 0);
914 testing.expect(count(u8, "h", "h") == 1);
915 testing.expect(count(u8, "hh", "h") == 2);
916 testing.expect(count(u8, "world!", "hello") == 0);
917 testing.expect(count(u8, "hello world!", "hello") == 1);
918 testing.expect(count(u8, " abcabc abc", "abc") == 3);
919 testing.expect(count(u8, "udexdcbvbruhasdrw", "bruh") == 1);
920 testing.expect(count(u8, "foo bar", "o bar") == 1);
921 testing.expect(count(u8, "foofoofoo", "foo") == 3);
922 testing.expect(count(u8, "fffffff", "ff") == 3);
923}
924
896/// Reads an integer from memory with size equal to bytes.len.925/// Reads an integer from memory with size equal to bytes.len.
897/// T specifies the return type, which must be large enough to store926/// T specifies the return type, which must be large enough to store
898/// the result.927/// the result.