简体   繁体   English

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

[英]How to compare a char to [ in Julia?

In Julia, I have some lines in a file that start with a [ char.在 Julia 中,我在文件中有一些以 [ 字符开头的行。 To get these lines, I try to compare the first char of each line to this char, but I seem to be missing some syntax.为了得到这些行,我尝试将每行的第一个字符与这个字符进行比较,但我似乎缺少一些语法。 So far, I've tried this, which returns false (for the first one) or doesn't accept the char (for the second):到目前为止,我已经尝试过这个,它返回 false (对于第一个)或不接受 char (对于第二个):

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

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

What would be the proper syntax to use here?在这里使用的正确语法是什么?

The canonical way would be to use startswith , which works with both single characters and longer strings:规范的方法是使用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

If you really want to get the first character of a string it is better to use first since indexing to strings is, in general, tricky.如果您真的想获取字符串的第一个字符,最好first使用,因为索引到字符串通常很棘手。

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

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

You comparing a string "[" not a char '['你比较一个字符串"["而不是一个字符'['

Hope it solve your problem希望它能解决你的问题

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

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