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"]
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.
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.
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.
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.
str.split(",").map {|i| i.to_i}
but the idea is same to you....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With