如何在 Julia 中将 char 与 [ 进行比较?

How to compare a char to [ in Julia?

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

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

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

此处使用的正确语法是什么?

你比较的是 string "[" 而不是 char '['

希望它能解决您的问题

规范的方法是使用 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

如果您真的想获取字符串的第一个字符,最好使用 first,因为一般来说,对字符串进行索引很棘手。

julia> first(line) == '['
true

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