How can I scroll every character in a string in Elixir?

Say I have a huge amount of text ~ 500 characters stored in a string, how can I scroll the string and increment the variable by 1 every time I encounter the character "a"?

+4
source share
2 answers

I think there are more understandable approaches to this that might work for you. Using regex:

Regex.scan(~r/a/, str) |> Enum.count

or dividing the string into Unicode characters, and then counting on it:

str |> String.graphemes |> Enum.count(fn(c) -> c == "a" end)

These are not very efficient approaches, but the performance impact should be negligible with a (relatively small!) Line, which is only 500 characters long.

, , . , .

defmodule Recursive do
  def count(str, <<c::utf8>>) do
    do_count(str, c, 0)
  end

  defp do_count(<<>>, _, acc) do
    acc
  end

  defp do_count(<<c::utf8, rest::binary>>, c, acc) do
    do_count(rest, c, acc + 1)
  end

  defp do_count(<<_::utf8, rest::binary>>, c, acc) do
    do_count(rest, c, acc)
  end
end

, , benchfella . " " @DeboraMartins, . .

# 500 Characters

split length         500000   5.90 µs/op
recursive            100000   10.63 µs/op
regex count          100000   24.35 µs/op
graphemes count       10000   118.29 µs/op


# 500.000 Characters

split length            100   11150.59 µs/op
recursive               100   12002.20 µs/op
regex count             100   25313.40 µs/op
graphemes count          10   218846.20 µs/op
+12

:

countSubstring = fn(_, "") -> 0
                 (str, sub) -> length(String.split(str, sub)) - 1 end

IO.puts countSubstring.(str, "a")

+7

All Articles