在Erlang中将整数转换为字符串

col*_*ung 56 string erlang

我知道,应该不惜一切代价避免使用Erlang字符串......

但如果我不这样做,我如何从5产生"5"?

特别是,有什么像io:format("〜p",[5])会返回格式化的字符串而不是打印到流?

wom*_*ble 146

还有integer_to_list/1,它完全符合你的要求,没有丑陋.

  • 他正在尝试将5转换为"5".因此,整数到字符串. (8认同)
  • 字符串在erlang中的ARE列表 (6认同)

Tho*_*mas 28

字符串是一个列表:

9> integer_to_list(123).  
"123"
Run Code Online (Sandbox Code Playgroud)


Luk*_*ard 14

以下可能不是最好的方式,但它有效:

1> lists:flatten(io_lib:format("~p", [35365])).
"35365"
Run Code Online (Sandbox Code Playgroud)

编辑:我发现以下函数有用:

%% string_format/2
%% Like io:format except it returns the evaluated string rather than write
%% it to standard output.
%% Parameters:
%%   1. format string similar to that used by io:format.
%%   2. list of values to supply to format string.
%% Returns:
%%   Formatted string.
string_format(Pattern, Values) ->
    lists:flatten(io_lib:format(Pattern, Values)).
Run Code Online (Sandbox Code Playgroud)

编辑2(回应评论):上面的函数来自我写了一段时间回来学习Erlang的小程序.我一直在寻找一个字符串格式化功能和发现的行为io_lib:format/2erl反直觉的,例如:

1> io_lib:format("2 + 2 = ~p", [2+2]).
[50,32,43,32,50,32,61,32,"4"]
Run Code Online (Sandbox Code Playgroud)

当时,我没有意识到@archaelus提到的输出设备的"自动展平"行为,因此得出的结论是上述行为不是我想要的.

今天晚上,我回到了这个程序,用string_format上面的函数替换了上面的函数io_lib:format.这引起的唯一问题是一些EUnit测试失败,因为他们期待一个扁平的字符串.这些很容易修复.

我同意@gleber和@womble使用此函数将整数转换为字符串是过分的.如果这就是您所需要的,请使用integer_to_list/1.吻!

  • 对于这个简单的任务,绝对不需要使用`io_lib:format/2`.`integer_to_list/1`就足够了. (25认同)
  • 遗憾的是,这是选定的答案,因为[womble](http://stackoverflow.com/a/588248/191191)是正确的答案. (3认同)
  • 而且,压扁所产生的iolist通常是浪费的.套接字/端口/文件/ IoDevices都在输出上变平,因此扁平化自己是多余的. (2认同)