Iggy
Iggy

Reputation: 5251

What's the shortest way to count substring occurrence in string? (Elixir)

Right now I have been using Regex.scan method:

Regex.scan(~r/do/i, “Do. Or do not. There is no try.") |> length

In Ruby, we can use .scan method: "Hello world".count "o" #=> 2

Is there a shorter method to count substring in a string with Elixir? No need for fancy regex, I just need to count how many substring in a string.

Upvotes: 2

Views: 3854

Answers (2)

ema
ema

Reputation: 5773

Not shorter, but an alternative:

"Hello world" |> String.graphemes |> Enum.count(& &1 == "o")

Thanks to @mudasobwa for the idiomatic way.

Upvotes: 8

adamkgray
adamkgray

Reputation: 1937

Another solution would be to split the string by the given substring, and then return the list length minus one

len = "foo bar foobar" |> String.split("foo") |> length()
total = len - 1

Upvotes: 8

Related Questions