How to convert Char to String in Julia?

In julia, Char and String are not comparable.

julia> 'a' == "a" false 

How to convert Char value to String value?

I tried the following functions, but none of them work.

 julia> convert(String, 'a') ERROR: MethodError: Cannot `convert` an object of type Char to an object of type String julia> String('a') ERROR: MethodError: Cannot `convert` an object of type Char to an object of type String julia> parse(String, 'a') ERROR: MethodError: no method matching parse(::Type{String}, ::Char) 
+8
source share
2 answers

Way

 string(c) 

eg.

 julia> string('🍕') "🍕" 

The string function works to turn something into its string representation, just like print ed. Really

 help?> string search: string String stringmime Cstring Cwstring RevString readstring string(xs...) Create a string from any values using the print function. julia> string("a", 1, true) "a1true" 
+10
source

I just wanted to add that the String constructor String can be successfully used in Vector{Char} , but not on a single character, for which you would use a string string function. The difference between the two really confused me.

Eventually:

  • To create a char vector from a string: a = Vector{Char}("abcd")
  • To create a string from a char vector: s = String(['a', 'b', 'c', 'd'])
  • To create a single character cs = string('a') : cs = string('a')
0
source

Source: https://habr.com/ru/post/1264546/


All Articles