Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to a list of integers in Erlang

Tags:

erlang

I am trying to convert a string to a list of integers.

  String = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08".

But

  lists:map(fun(X) -> string:to_integer(X) end, string:tokens(String, " ")).

just gives me...

  [{8,[]}, {2,[]}, {22,[]}, {97,[]}, ... , {91,[]}, {8,[]}]

Can someone perhaps tell me what a good/nice way would be to get?

  [8,2,22,97...91,8]

(Or do I need a helper function?)


1 Answers

This works:

String = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08".
lists:map(fun(X) -> {Int, _} = string:to_integer(X), 
                    Int end, 
          string:tokens(String, " ")).

> [8,2,22,97,38,15,0,40,0,75,4,5,7,78,52,12,50,77,91,8]

See, string:to_integer returns not a single integer, but a tuple:

to_integer(String) -> {Int,Rest} | {error,Reason}

... so you have to extract the first element from this tuple to get the actual number.

like image 74
raina77ow Avatar answered Feb 02 '26 01:02

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!