Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions lib/elixir/lib/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,38 @@ defmodule String do
{left, right}
end

@doc ~S"""
Counts the number of occurrences of a `pattern` in a `string`.

## Examples

iex> String.count("hello world", "o")
2

iex> String.count("hello world", "l")
3

iex> String.count("hello world", "x")
0

iex> String.count("hello world", ~r/o/)
2

iex> pattern = :binary.compile_pattern([" ", "!"])
iex> String.count("foo bar baz!!", pattern)
4

"""
@spec count(t, pattern | Regex.t()) :: non_neg_integer
@doc since: "1.19.0"
def count(string, pattern) when is_struct(pattern, Regex) do
Kernel.length(Regex.scan(pattern, string, return: :index))
end

def count(string, pattern) do
Kernel.length(:binary.matches(string, pattern))
end

@doc ~S"""
Returns `true` if `string1` is canonically equivalent to `string2`.

Expand Down