string 如何在 Erlang 中将整数转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/588003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an integer to a string in Erlang?
提问by collapsinghrung
I know strings in Erlang can be costly to use. So how do I convert "5"
to 5
?
我知道 Erlang 中的字符串使用起来很昂贵。那么我如何转换"5"
为5
?
Is there anything like io:format("~p",[5])
that would return a formatted string instead of printing to a stream?
有没有类似的东西io:format("~p",[5])
会返回格式化的字符串而不是打印到流?
采纳答案by Luke Woodward
The following is probably not the neatest way, but it works:
以下可能不是最简洁的方法,但它有效:
1> lists:flatten(io_lib:format("~p", [35365])).
"35365"
EDIT: I've found that the following function comes in useful:
编辑:我发现以下功能很有用:
%% 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)).
EDIT 2(in response to comments): the above function came from a small program I wrote a while back to learn Erlang. I was looking for a string-formatting function and found the behaviour of io_lib:format/2
within erl
counter-intuitive, for example:
编辑 2(回应评论):上述函数来自我前一段时间为学习 Erlang 编写的一个小程序。我一直在寻找一个字符串格式化功能和发现的行为io_lib:format/2
中erl
反直觉的,例如:
1> io_lib:format("2 + 2 = ~p", [2+2]).
[50,32,43,32,50,32,61,32,"4"]
At the time, I was unaware of the 'auto-flattening' behaviour of output devices mentioned by @archaelus and so concluded that the above behaviour wasn't what I wanted.
当时,我不知道@archaelus 提到的输出设备的“自动展平”行为,因此得出结论,上述行为不是我想要的。
This evening, I went back to this program and replaced calls to the string_format
function above with io_lib:format
. The only problems this caused were a few EUnit tests that failed because they were expecting a flattened string. These were easily fixed.
今天晚上,我回到这个程序并将对上述string_format
函数的调用替换为io_lib:format
. 这引起的唯一问题是一些 EUnit 测试失败,因为他们期待一个扁平的字符串。这些很容易解决。
I agree with @gleber and @womble that using this function is overkill for converting an integer to a string. If that's all you need, use integer_to_list/1
. KISS!
我同意@gleber 和@womble 的观点,即使用此函数将整数转换为字符串是过度的。如果这就是您所需要的,请使用integer_to_list/1
. 吻!
回答by womble
There's also integer_to_list/1
, which does exactly what you want, without the ugliness.
还有integer_to_list/1
,它完全符合你的要求,没有丑陋。
回答by Thomas
A string is a list:
字符串是一个列表:
9> integer_to_list(123).
"123"
回答by Gordon Guthrie
回答by Michael Neale
lists:concat([Number]). also works.
列表:concat([数字])。也有效。