Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Char to String in Julia?

Tags:

string

char

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)
like image 473
Jay Wong Avatar asked Feb 21 '17 22:02

Jay Wong


People also ask

How do I convert a char to a string?

We can convert a char to a string object in java by using the Character. toString() method.

How do you replace a character in a string in Julia?

The replace() is an inbuilt function in julia that is used to replace a word or character with the specified string or character. Parameters: s::AbstractString: Specified string. pattern=>Word: Pattern is searched from the given sentence and then that pattern is replaced with the word.

How do you add strings to Julia?

Using '*' operator It is used to concatenate different strings and/or characters into a single string. We can concatenate two or more strings in Julia using * operator.


2 Answers

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"
like image 166
Fengyang Wang Avatar answered Nov 03 '22 23:11

Fengyang Wang


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')
like image 40
xji Avatar answered Nov 04 '22 00:11

xji