Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia convert String to Char, or convert Array{SubString{String},1} to char

Tags:

string

char

julia

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]))
like image 621
Al Bro Avatar asked Jan 28 '20 09:01

Al Bro


People also ask

Can you convert string to char array?

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.

How do you split strings in Julia?

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' '/' ...


2 Answers

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.

like image 108
rapasite Avatar answered Oct 27 '22 23:10

rapasite


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

like image 27
Jakob Nissen Avatar answered Oct 27 '22 23:10

Jakob Nissen