| ... | @@ -1704,6 +1704,26 @@ test count { | ... | @@ -1704,6 +1704,26 @@ test count { |
| 1704 | try testing.expect(count(u8, "owowowu", "owowu") == 1); | 1704 | try testing.expect(count(u8, "owowowu", "owowu") == 1); |
| 1705 | } | 1705 | } |
| 1706 | | 1706 | |
| | 1707 | /// Returns the number of needles inside the haystack |
| | 1708 | pub fn countScalar(comptime T: type, haystack: []const T, needle: T) usize { |
| | 1709 | var i: usize = 0; |
| | 1710 | var found: usize = 0; |
| | 1711 | |
| | 1712 | while (findScalarPos(T, haystack, i, needle)) |idx| { |
| | 1713 | i = idx + 1; |
| | 1714 | found += 1; |
| | 1715 | } |
| | 1716 | |
| | 1717 | return found; |
| | 1718 | } |
| | 1719 | |
| | 1720 | test countScalar { |
| | 1721 | try testing.expectEqual(0, countScalar(u8, "", 'h')); |
| | 1722 | try testing.expectEqual(1, countScalar(u8, "h", 'h')); |
| | 1723 | try testing.expectEqual(2, countScalar(u8, "hh", 'h')); |
| | 1724 | try testing.expectEqual(3, countScalar(u8, " abcabc abc", 'b')); |
| | 1725 | } |
| | 1726 | |
| 1707 | /// Returns true if the haystack contains expected_count or more needles | 1727 | /// Returns true if the haystack contains expected_count or more needles |
| 1708 | /// needle.len must be > 0 | 1728 | /// needle.len must be > 0 |
| 1709 | /// does not count overlapping needles | 1729 | /// does not count overlapping needles |