Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is string "11" less than string "3"? [duplicate]

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 :-)

like image 720
jilseego Avatar asked Jun 02 '12 14:06

jilseego


People also ask

Can a string be less than another string?

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.

Can you use == for strings?

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.

Does == work for strings C++?

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.

How do you determine which string is greater?

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).


1 Answers

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 
like image 147
Quentin Avatar answered Sep 18 '22 18:09

Quentin