if ('11' < '3') alert('true');
It's obvious that it's not comparing them by length but by encoding instead. However, I don't understand how it works. I need some explanation :-)
In other words, strings are compared letter-by-letter. The algorithm to compare two strings is simple: Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
In C++ the == operator is overloaded for the string to check whether both strings are same or not. If they are the same this will return 1, otherwise 0. So it is like Boolean type function.
Java String compareTo() Method The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).
Strings are compared lexicographicaly. i.e. character by character until they are not equal or there aren't any characters left to compare. The first character of '11' is less than the first character of '3'.
> '11' < '3' true > '31' < '3' false > '31' < '32' true > '31' < '30' false
If we use letters then, since b
is not less than a
, abc
is not less than aaa
, but since c
is less than d
, abc
is less than abd
.
> 'abc' < 'aaa' false > 'abc' < 'abd' true
You can explicitly convert strings to numbers:
> +'11' < '3' false
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