代码之家  ›  专栏  ›  技术社区  ›  Charles Okwuagwu

如何在elixir/erlang中实现高效的to_ascii函数

  •  1
  • Charles Okwuagwu  · 技术社区  · 7 年前

    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
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Aleksei Matiushkin    7 年前

    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
  •  5
  •   Hynek -Pichi- Vychodil Paulo Suassuna    7 年前

    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!"