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]
.
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.
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').
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.
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.
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.
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