Hello everyone,

I recently came across the need to count all the occurrences of a pattern 
inside a String. First, I used `String.split(string, pattern)` and then 
counted the number of parts (-1). Then it was suggested to me to use 
`:binary.matches` instead and simply count the number of entries. This is 
quite straightforward, but you need to know about `:binary.matches`, so I 
wondered if the Elixir `String` module should include something like 
`String.count/2` instead:

@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

"""
@spec count(t, pattern) :: non_neg_integer
@doc since: "1.19.0"
def count(string, pattern) do
Enum.count(:binary.matches(string, pattern))
end

As you can see, the implementation is quite straightforward, so I'm not 
sure if it's worth to be included. Let me know what you think!

Happy to send a PR.

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion visit 
https://groups.google.com/d/msgid/elixir-lang-core/a603547c-689c-4a05-9c2c-5e8e6a162968n%40googlegroups.com.

Reply via email to