Reputation: 5251
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
Reputation: 5773
Not shorter, but an alternative:
"Hello world" |> String.graphemes |> Enum.count(& &1 == "o")
Thanks to @mudasobwa for the idiomatic way.
Upvotes: 8
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