简体   繁体   English

如何在Julia中将Char转换为String?

[英]How to convert Char to String in Julia?

In julia, Char and String are not comparable. 在朱莉娅,Char和String没有可比性。

julia> 'a' == "a"
false

How can I convert a Char value to a String value? 如何将Char值转换为String值?

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)

The way is 方式是

string(c)

eg 例如

julia> string('🍕')
"🍕"

The string function works to turn anything into its string representation, in the same way it would be print ed. string函数用于将任何内容转换为字符串表示形式,与print方式相同。 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"

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. 只是想补充一点,大写的String构造函数可以在Vector{Char}上成功使用,而不是在一个char上,你可以使用小写string函数。 The difference between these two really got me confused. 这两者之间的区别让我很困惑。

In summary: 综上所述:

  • To create a char vector from a string: a = Vector{Char}("abcd") 要从字符串创建char矢量: a = Vector{Char}("abcd")
  • To create a string from a char vector: s = String(['a', 'b', 'c', 'd']) 从char向量创建一个字符串: s = String(['a', 'b', 'c', 'd'])
  • To create a string from a single char: cs = string('a') 从单个char创建字符串: cs = string('a')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM