6

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 ?

2 Answers 2

12

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.

7

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

Hope it solve your problem

Not the answer you're looking for? Browse other questions tagged or ask your own question.