【发布时间】:2018-06-14 03:52:23
【问题描述】:
您将如何在 Elixir(或 Erlang)中实现高效的 to_ascii 函数?
扫描字符串的每个字符并调用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
【问题讨论】: