将整数转换为Erlang中的字符串 [英] convert an integer to a string in Erlang

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

问题描述

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



但如果我不这样做,我如何从5生成5 ?特别是,有没有像io:format(〜p,[5])的任何东西会返回一个格式化的字符串而不是打印到流?



/ p>

解决方案

以下可能不是最整洁的方式,但它的作品:

  1>列表:flatten(io_lib:format(〜p,[35365]))。 
35365

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

  %% string_format / 2 
%%喜欢io:format,除了它返回评估字符串而不是写
%%它到标准输出。
%%参数:
%% 1.格式字符串类似于io:format使用的格式。
%% 2.要提供给格式字符串的值列表。
%%返回:
%%格式化的字符串。
string_format(Pattern,Values) - >
列表:flatten(io_lib:format(Pattern,Values))。

编辑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]

当时,我并不了解@archaelus提及的输出设备的自动展平行为,因此得出结论,上述行为并不是我想要的。



今天晚上,我回到这个程序,并用 io_lib:format string_format 函数C>。这个唯一的问题是几次EUnit测试失败,因为他们期待一个扁平的字符串。这些都很容易修复。



我同意@gleber和@womble,使用此函数将整数转换为字符串是过分的。如果这是你需要的,使用 integer_to_list / 1 。 KISS!


I know, Erlang strings should be avoided at all costs...

but if I'm not doing that, how do I produce "5" from 5?

in particular, 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"

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:

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.

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.

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天全站免登陆