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

Jay*_*ong 10 string char julia

在朱莉娅,Char和String没有可比性.

julia> 'a' == "a"
false
Run Code Online (Sandbox Code Playgroud)

如何将Char值转换为String值?

我尝试了以下功能,但它们都不起作用.

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)
Run Code Online (Sandbox Code Playgroud)

Fen*_*ang 12

方式是

string(c)
Run Code Online (Sandbox Code Playgroud)

例如

julia> string('')
""
Run Code Online (Sandbox Code Playgroud)

string函数可以将任何内容转换为字符串表示形式,就像print编辑它一样.确实

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"
Run Code Online (Sandbox Code Playgroud)


xji*_*xji 7

只是想补充一点,大写String构造函数可以在 上成功使用Vector{Char},但不能在单个字符上使用,为此您可以使用小写string函数。这两者之间的区别确实让我很困惑。

总之:

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