Search code examples
c++stringcomparison

Comparing strings using std::string::compare, c++


I have a question:

Let's say there are two std::strings and I want to compare them, there is the option of using the compare() function of the string class but I also noticed that it is possible using simple < > != operators (both of the cases are possible even if I don't include the <string> library). Can someone explain why the compare() function exists if a comparison can be made using simple operators?

btw I use Code::Blocks 13.12 here is an example of my code:

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::getline;

int main()
{
    string temp1, temp2;
    cout << "Enter first word: ";
    getline (cin,temp1);
    cout << "Enter second word: ";
    getline (cin,temp2);
    cout << "First word: " << temp1 << endl << "Second word: " << temp2 << endl;
    if (temp1 > temp2)
    {
        cout << "One" << endl;
    }
    if (temp1.compare(temp2) < 0)
    {
        cout << "Two" << endl;
    }
    return 0;
}    

Solution

  • .compare() returns an integer, which is a measure of the difference between the two strings.

    • A return value of 0 indicates that the two strings compare as equal.
    • A positive value means that the compared string is longer, or the first non-matching character is greater.
    • A negative value means that the compared string is shorter, or the first non-matching character is lower.

    operator== simply returns a boolean, indicating whether the strings are equal or not.

    If you don't need the extra detail, you may as well just use ==.