Jay Wang
Jay Wang

Reputation: 2840

How to convert Char to String in Julia?

In julia, Char and String are not comparable.

julia> 'a' == "a"
false

How can I convert a Char value to a String value?

I have 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)

Upvotes: 22

Views: 8774

Answers (2)

xji
xji

Reputation: 8247

Just wanted to add that the uppercase String constructor can be successfully used on Vector{Char}, just not on a single char, for which you'd use the lowercase string function. The difference between these two really got me confused.

In summary:

  • 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 string from a single char: cs = string('a')

Upvotes: 8

Fengyang Wang
Fengyang Wang

Reputation: 12051

The way is

string(c)

e.g.

julia> string('🍕')
"🍕"

The string function works to turn anything into its string representation, in the same way it would be printed. Indeed

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"

Upvotes: 24

Related Questions