What does the .compare function do? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
15th Jul 2018, 5:30 PM
Mukul
Mukul - avatar
8 Answers
+ 3
Mukul There's no big of deal there. The mechanism behind the compare function looks through the first string let's say "dog" then the second one let's say "cat". It begins its comparison by looking at the first character of the first string which is 'd' and then first character of the second string which is 'c'. Clearly 'd' is greater than 'c' and there's no need for comparing the rest of the characters together, so the whole thing returns 1 which tells us that the first string is greater than the second one. string dog = "dog"; string cat = "cat"; // All three possibilities of comparison cout << dog.compare(cat) << endl; // 1 cout << cat.compare(dog) << endl; // -1 cout << dog.compare(dog) << endl; // 0 Alexander Sokolov Indeed, it's case sensitive. Try to compare dog = "Dog" and cat = "cat" as dog.compare(cat)
15th Jul 2018, 8:25 PM
Babak
Babak - avatar
+ 3
Hello, Mukul ! compare() — Compares the two specified "String" objects whether or not case-sensitive and returns an integer that indicates their relative position in the sort order. Good luck with programming on SoloLearn! https://www.sololearn.com/Course/CPlusPlus/?ref=app
15th Jul 2018, 5:57 PM
Alexander Sokolov
Alexander Sokolov - avatar
+ 1
Mukul the integer -1, 0 or 1 depending on the sort order position of the first string compared to the second one
15th Jul 2018, 6:54 PM
hinanawi
hinanawi - avatar
+ 1
Thanq you C++ Soldier (Babak) I understand it
15th Jul 2018, 8:34 PM
Mukul
Mukul - avatar
0
What integer
15th Jul 2018, 6:00 PM
Mukul
Mukul - avatar
0
Plz tell me how exactly
15th Jul 2018, 6:58 PM
Mukul
Mukul - avatar
0
I couldn't really understand much but thanks guyz.
15th Jul 2018, 7:21 PM
Mukul
Mukul - avatar