Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from string to array?

Tags:

julia

If s = "1 2 3 4 5", how could we obtain an Integer Array from this. I would like to return a 5 element Array{Int64,1} [1; 2; 3; 4; 5].

like image 208
Abhijith Avatar asked Sep 19 '16 12:09

Abhijith


People also ask

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

The string. split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.

Can we convert string to array in C?

1. The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').

Which function will use to convert from string to array?

str_split() Function This is an in-built PHP method that is used to convert a string into an array by breaking the string into smaller sub-strings of uniform length and storing them in an array.


2 Answers

As @isebarn used, split(s) is useful for splitting a string up into words (splitting by default at spaces):

julia> s = "1 2 3 4 5"
"1 2 3 4 5"

julia> split(s)
5-element Array{SubString{String},1}:
 "1"
 "2"
 "3"
 "4"
 "5"

Now you can use an array comprehension:

[parse(Int, ss) for ss in split(s)]

Here, parse(Int, ss) parses a string ss into an integer.

Note also that this returns a one-dimensional vector, not a two-dimensional array. There is no reason to prefer a two-dimensional array here -- this is a naturally one-dimensional object.

like image 157
David P. Sanders Avatar answered Oct 27 '22 00:10

David P. Sanders


If you are using version 0.5 or later, you can also do this:

int_s = parse.(split(s))

The trailing dot is the new compact broadcast notation. Possibly, this will be the preferred syntax in future versions.

like image 45
DNF Avatar answered Oct 27 '22 01:10

DNF