Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string of numbers to array of numbers

In my app, I have a textfield in which the user enters something like this

"1,2,3,4"

which gets stored to the database. Now, when I want to use the inner numbers, i have two options:

"1,2,3,4".split(',')

OR

string.scan(/\d+/) do |x|
    a << x
end

Both ways i get an array like

 ["1","2","3","4"] 

and then i can use the numbers by calling to_i on each one of them.
Is there a better way of doing this, that converts

"1,2,3" to [1,2,3] and not ["1","2","3"]
like image 666
Jatin Ganhotra Avatar asked Dec 22 '10 07:12

Jatin Ganhotra


People also ask

How do you convert a string of numbers to an array of numbers?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

How do I turn an array of numbers into an array of strings?

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings. Copied! const arrOfNum = [1, 2, 3]; const arrOfStr = arrOfNum.

Can you convert a string to an array?

We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.

How do you convert a string of numbers to an array of numbers in Python?

To convert String to array in Python, use String. split() method. The String . split() method splits the String from the delimiter and returns the splitter elements as individual list items.


1 Answers

str.split(",").map {|i| i.to_i}

but the idea is same to you....

like image 118
Jimmy Huang Avatar answered Oct 18 '22 16:10

Jimmy Huang