4
votes

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]))
3

3 Answers

5
votes

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.

4
votes

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}.

0
votes

Got there eventually

collect(mdSplit[2])[1]