【问题标题】:how to implement an efficient to_ascii function in Elixir/ Erlang如何在 Elixir/Erlang 中实现高效的 to_ascii 函数
【发布时间】: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

【问题讨论】:

    标签: erlang elixir ascii


    【解决方案1】:

    使用Kernel.SpecialForms.for/1理解with :into keyword argument

    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"
    

    【讨论】:

    • 显然不是我;责怪何塞 :)
    【解决方案2】:

    在二郎中

    1> Bin = <<"hello привет ¡hola!"/utf8>>.
    <<104,101,108,108,111,32,208,191,209,128,208,184,208,178,
      208,181,209,130,32,194,161,104,111,108,97,33>>
    2> << <<C>> || <<C>> <= Bin, C >= 32, C =< 127 >>. 
    <<"hello  hola!">>
    3> [ C || <<C>> <= Bin, C >= 32, C =< 127 ].      
    "hello  hola!"
    

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 2021-12-24
      • 2015-12-09
      • 2023-03-08
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 2015-12-10
      • 2016-04-29
      相关资源
      最近更新 更多