首页 > 解决方案 > 如何在 Elixir/Erlang 中实现高效的 to_ascii 函数

问题描述

你将如何to_ascii在 Elixir(或 Erlang)中实现一个高效的函数?

扫描字符串的每个字符并调用String.printable?似乎是一个非常糟糕的选择

  def to_ascii(s) do
    case String.printable?(s) do
      true -> s
      false -> _to_ascii(String.codepoints(s), "")
    end
  end

  defp _to_ascii([], acc), do: acc
  defp _to_ascii([c | rest], acc) when ?c in 32..127, do: _to_ascii(rest, acc <> c)
  defp _to_ascii([_ | rest], acc), do: _to_ascii(rest, acc)

例子:

s_in = <<"hello", 150, " ", 180, "world", 160>>
s_out = "hello world" # valid ascii only i.e 32 .. 127

标签: erlangelixirascii

解决方案


使用带有关键字参数Kernel.SpecialForms.for/1的理解::into

s = "hello привет ¡hola!"
for <<c <- s>>, c in 32..127, into: "", do: <<c>>
#⇒ "hello  hola!"

s = <<"hello", 150, "world", 160>>
for <<c <- s>>, c in 32..127, into: "", do: <<c>>
#⇒ "helloworld"

推荐阅读