Reputation: 443
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]))
Upvotes: 6
Views: 5451
Reputation: 71
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.
Upvotes: 7
Reputation: 1991
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}
.
Upvotes: 5