I am new to the Julia language and see some strange behavior when comparing a substring to a character.
I would think that the first comparison below, at least, should evaluate to true
.
Could someone please show me how to compare these two values and (bonus) point me in the direction as to why this counterintuitive result is the case?
julia> sq = "abcd"
julia> sq[1] == "a"
false
julia> isequal(sq[1],"a")
false
sq[1]
returns a Char
. Use sq[1:1]
to get a String
.
You can check what sq[1]
returns in REPL:
julia> sq[1]
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
so you have:
julia> sq[1] == 'a'
true
as this compares Char
to Char
.
on the other hand with sq[1:1]
you have:
julia> sq[1:1]
"a"
julia> sq[1:1] == "a"
true
The reason for this behavior is that strings are considered as collections. Similarly if you have an array x = [1,2,3]
you do not expect that x[1] == [1]
but rather x[1] == 1
.
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