Skip to content

Commit 0fb90f1

Browse files
authored
Add String.count/2 (#14448)
1 parent 87dd05e commit 0fb90f1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

lib/elixir/lib/string.ex

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,51 @@ defmodule String do
709709
{left, right}
710710
end
711711

712+
@doc ~S"""
713+
Counts the number of non-overlapping occurrences of a `pattern` in a `string`.
714+
715+
In case the pattern is an empty string, the function returns 1 + the number of graphemes
716+
in the string.
717+
718+
## Examples
719+
720+
iex> String.count("hello world", "o")
721+
2
722+
723+
iex> String.count("hello world", "l")
724+
3
725+
726+
iex> String.count("hello world", "x")
727+
0
728+
729+
iex> String.count("hello world", ~r/o/)
730+
2
731+
732+
iex> String.count("Hellooo", "oo")
733+
1
734+
735+
iex> String.count("hello world", "")
736+
12
737+
738+
The `pattern` can also be a compiled pattern:
739+
740+
iex> pattern = :binary.compile_pattern([" ", "!"])
741+
iex> String.count("foo bar baz!!", pattern)
742+
4
743+
744+
"""
745+
@spec count(t, pattern | Regex.t()) :: non_neg_integer
746+
@doc since: "1.19.0"
747+
def count(string, <<>>), do: length(string) + 1
748+
749+
def count(string, pattern) when is_struct(pattern, Regex) do
750+
Kernel.length(Regex.scan(pattern, string, return: :index))
751+
end
752+
753+
def count(string, pattern) do
754+
Kernel.length(:binary.matches(string, pattern))
755+
end
756+
712757
@doc ~S"""
713758
Returns `true` if `string1` is canonically equivalent to `string2`.
714759

0 commit comments

Comments
 (0)