Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparision of strings with numbers, how does it work

Tags:

c++

string a = "10";
string b = "20";
if(a>b)
  std::cout<<a;
else
  std::cout<<b;

The above code gives me correct output, but I don't know how? Can someone please explain me how strings with numbers are compared in this case.

like image 904
Sivabushan Avatar asked Feb 08 '23 14:02

Sivabushan


1 Answers

It works just like any string comparison:

The two strings are compared lexicographically, and since the character '2' comes after the character '1', we have "20" > "10".

Let's do another example, taken from the comments: Given "100" and "99", we compare their first characters, see that '9' comes after '1', and so we get "99" > "100".

like image 121
Baum mit Augen Avatar answered Feb 16 '23 04:02

Baum mit Augen