I want to convert an array of SubStrings into either Char or String values.
I split a String to get an array of elements fine
mdSplit = split(mdSub,r"[ ]+")
4-element Array{SubString{String},1}:
"73"
"G"
"T"
""
but now I want to iterate through this array, and if the value is a character I'm going convert that character to a Char, or make a copy of it as a char have tried both convert and parse
convert(Char,string(mdSplit[2]))
char[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string. char charAt(int index) : This method returns character at specific index of string.
Similarly, you can use split() to split the string and count the results: julia> split(s, "") 55-element Array{Char,1}: '/' 'U' 's' 'e' 'r' 's' '/' ...
only()
seems to be the right way:
julia> string_a = "a"
"a"
julia> char_a = only(string_a)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
others solutions:
mdSplit[2][1]
or mdSplit[2][end]
or first(mdSplit[2])
or last(mdSplit[2])
All change a 1 size String to a Char.
First, you might want to reconsider whether you really want an array of String and Char. Isn't it nicer to have an array with only one element type?
Anyway, you can convert a SubString to a String or Char like this:
function string_or_char(s::SubString)
length(s) == 1 && return first(s)
return String(s)
end
Note that this function is type unstable. Then put it in an array like this:
arr = Union{Char,String}[]
for i in split_string
push!(arr, string_or_char(i))
end
Alternatively, you can make your array like this:
[string_or_char(s) for s in split_string]
. But this will be type unstable itself, and can return any of Vector{Char}
, Vector{String}
or Vector{Any}
.
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