2012年4月15日 星期日

[Erlang] 如何用format的方式產生字串

其實字串在Erlang中叫做List of chars,但是為了讓標題變得比較容易找到還是用通俗講法的字串,也就是string。

平常我們使用format字串的時機其實是在io:format/2的時候,這也是大多數Erlang書籍範例中會一直出現的,但是io:format/2其實只是一個可以把結果輸出stdout的function而已,並不能產生字串來處理或是存入變數,書籍上也鮮少提到說產生format字串的方式。

其實Document中還有一另外一個library叫做io_lib,裡面有個io_lib:format/2,用法跟io:format/2大同小異,唯一的差別就是他會return一個char list。

所以這時候就可以用下面這個statement:

StringData = io_lib:format("~p~p", [StringOne, StringTwo]). 

StringData就會被存入一個format之後的字串了。

Original Link: How do you get the result from io:format into a string

Documentation Link: Doc - io_lib:format/2

沒有留言:

張貼留言