[Proposal] Add String.count/2

114 views
Skip to first unread message

Steffen Deusch

unread,
Apr 17, 2025, 7:48:11 AMApr 17
to elixir-lang-core
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.

Roman Smirnov

unread,
Apr 17, 2025, 8:28:16 AMApr 17
to elixir-lang-core
Interesting. I didn't know about :binary.matches/2

I usually use that way to solve the original task:
Regex.scan(pattern, string) |> Enum.count

But I guess would be nice to have a helper for it. Maybe not `count` (could be ambiguous, b/c it's a synonym of length), maybe substr_count

четверг, 17 апреля 2025 г. в 14:48:11 UTC+3, steffen...@dashbit.co:

José Valim

unread,
Apr 17, 2025, 8:46:15 AMApr 17
to elixir-l...@googlegroups.com
For consistency, our version of String.count should also accept regexes as patterns, as supported in String.replace and others.


--
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-co...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/elixir-lang-core/0e7f4fbb-a786-4d1d-a3f9-d76712e4eae4n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages