如何在Erlang中将整数转换为字符串? [英] How to convert an integer to a string in Erlang?

查看:124
本文介绍了如何在Erlang中将整数转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Erlang中的字符串使用起来会很昂贵。那么如何将 5 转换为 5

I know strings in Erlang can be costly to use. So how do I convert "5"to 5?

是否有像 io:format(〜p,[5])这样的东西会返回格式化的字符串而不是打印到流中?

Is there anything like io:format("~p",[5]) that would return a formatted string instead of printing to a stream?

推荐答案

以下可能不是最整洁的方法,但它可行:

The following is probably not the neatest way, but it works:

1> lists:flatten(io_lib:format("~p", [35365])).
"35365"

编辑:我发现以下功能很有用:

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)).

编辑2 (回复评论):以上功能来自我写了一个小程序来学习Erlang。我在寻找一个字符串格式函数,发现 erl 中的 io_lib:format / 2 的行为与直觉相反,例如:

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:

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

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

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.

今天晚上,我回到该程序,并用 io_lib:format string_format 函数的调用c>。造成的唯一问题是一些EUnit测试失败,因为它们期望字符串变平。这些很容易修复。

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.

我同意@gleber和@womble的观点,即使用此函数将整数转换为字符串是过大的。如果您只需要这些,请使用 integer_to_list / 1 。吻!

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!

这篇关于如何在Erlang中将整数转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆