Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a char to [ in Julia?

In Julia, I have some lines in a file that start with a [ char. 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) :

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

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

What would be the proper syntax to use here ?

like image 811
J. Schmidt Avatar asked Apr 30 '20 10:04

J. Schmidt


Video Answer


2 Answers

The canonical way would be to use startswith, which works with both single characters and longer strings:

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.

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

See https://docs.julialang.org/en/v1/manual/strings/#Unicode-and-UTF-8-1 for more details about string indexing.

like image 188
fredrikekre Avatar answered Sep 27 '22 23:09

fredrikekre


You comparing a string "[" not a char '['

Hope it solve your problem

like image 24
lupaulus Avatar answered Sep 28 '22 00:09

lupaulus