如何将字符与 Julia 中的 [ 进行比较?

J. *_*idt 6 string file character special-characters julia

在 Julia 中,我在文件中有一些以 [ 字符开头的行。为了得到这些行,我尝试将每一行的第一个字符与这个字符进行比较,但我似乎缺少一些语法。到目前为止,我已经尝试过这个,它返回 false(第一个)或不接受字符(第二个):

if (line[1] == "[")

if (line[1] == "\[")

在这里使用的正确语法是什么?

fre*_*kre 12

规范的方法是使用startswith,它适用于单个字符和更长的字符串:

julia> line = "[hello, world]";

julia> startswith(line, '[') # single character
true

julia> startswith(line, "[") # length-1 string
true

julia> startswith(line, "[hello") # longer string
true
Run Code Online (Sandbox Code Playgroud)

如果您真的想获取字符串的第一个字符,最好使用,first因为索引字符串通常很棘手。

julia> first(line) == '['
true
Run Code Online (Sandbox Code Playgroud)

有关字符串索引的更多详细信息,请参阅https://docs.julialang.org/en/v1/manual/strings/#Unicode-and-UTF-8-1


lup*_*lus 7

您比较的是字符串 "["而不是 字符 '['

希望它能解决你的问题