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 ?
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.
You comparing a string "["
not a char '['
Hope it solve your problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With