Erlang 玩轉字符串

erlang的漢字字符串和二進制的相互轉換 

Eshell V11.0  (abort with ^G)
1>  unicode:characters_to_binary("中國").
<<195,150,195,144,194,185,195,186>>
2> <<"中國"/utf8>>.
<<195,150,195,144,194,185,195,186>>
3>

erlang將字符串轉換成erlang數據結構

1> Str1 = "#{a=>b,c=>d}".
"#{a=>b,c=>d}"
2> {ok,Tokens,_} = erl_scan:string(Str1 ++ "."). %% 要解析的字符串一定要以.結尾
{ok,[{'#',1},
     {'{',1},
     {atom,1,a},
     {'=>',1},
     {atom,1,b},
     {',',1},
     {atom,1,c},
     {'=>',1},
     {atom,1,d},
     {'}',1},
     {dot,1}],
    1}
3> {ok, #{a=>b,c=>d}} = erl_parse:parse_term(Tokens).
* 2: illegal pattern
4>

將任何術語轉換爲字符串

Eshell V11.0  (abort with ^G)
1> R= io_lib:format("~p",[yourtermhere]).
["yourtermhere"]
2>  lists:flatten(R).
"yourtermhere"
3>
Eshell V11.0  (abort with ^G)
1> R= io_lib:format("~p",[yourtermhere]).
["yourtermhere"]
2> lists:flatten(R).
"yourtermhere"
3>
Eshell V11.0  (abort with ^G)
1> io_lib:format("~.2f", [789.1234]).
"789.12"
2> io_lib:format("~.1f", [789.1234]).
"789.1"

浮點數轉字符串

Eshell V11.0  (abort with ^G)
1> float_to_list(223.44456,[{decimals,0}]).
"223"
2> float_to_list(223.44456,[{decimals,6}]).
"223.444560"
3> float_to_list(223.44456,[{decimals,6},compact]).
"223.44456"
4>

第三方庫

Erlang / Elixir 的快速編碼轉換庫

https://github.com/processone/iconv

Eshell V10.2.1  (abort with ^G)
1> application:start(iconv).
ok
2> FromEncoding = <<"utf-8">>. 
<<"utf-8">>
3> ToEncoding = <<"iso8859-15">>.
<<"iso8859-15">>
4> Text = <<"Hello">>.
<<"Hello">>
5> iconv:convert(FromEncoding, ToEncoding, Text).            
<<"Hello">>

持續更新中......

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章