1.用io:format/2的~p打印中文,出來的是unicode編碼的list;
用io:format/2的~ts打印中文,就可以打印出中文
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
1> io:format("test===~p~n",["測試"]).
test===[27979,35797]
ok
2> io:format("test====~ts~n",["測試"]).
test====測試
ok
2.代碼中的中文都是以utf8編碼過的,即把unicode編碼過的list再次用utf8編碼
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
3> xmerl_ucs:to_utf8([27979,35797]).
[230,181,139,232,175,149]
可以看到utf8編碼後是壹個0-255數組成的壹個list,這是項目中經常輸出的中文字符的日誌。
3.為了輸出中文,需要把utf8轉換成unicode編碼,即
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
4> unicode:characters_to_list(list_to_binary([230,181,139,232,175,149])).
[27979,35797]
5> io:format("test===~ts~n",[[27979,35797]]).
test===測試
ok
為了方便,寫成壹個方法,可以在項目中直接調用。
[html] view plain copy
print?在CODE上查看代碼片派生到我的代碼片
-module(print_log).
-export([log/2,
test/0]).
log(Format, Data)->
L = get_format_list(Format),
DataList=
lists:map(
fun({1, X}) ->
unicode:characters_to_list(iolist_to_binary(X));
({0, X}) ->
X
end, lists:zip(L, Data)),
io:format(Format,DataList).
get_format_list(Format) ->
get_format_list(Format, []).
get_format_list([], Acc) ->
Acc;
get_format_list([$~|L], Acc) ->
case L of
"ts" ++ Other ->
get_format_list(Other, Acc ++ [1]);
"n" ++ Other ->
get_format_list(Other, Acc);
_ ->
get_format_list(L, Acc ++ [0])
end;
get_format_list([_H|L],Acc) ->
get_format_list(L, Acc).
test()->
log("test===~ts",["測試"]).