C++ string compare() Function
Example
Compare a string with two other strings:
string txt = "Apple";
cout << (txt.compare("Apple") == 0 ? "Equal" : "Not equal") << "\n";
cout << (txt.compare("Banana") < 0 ? "Apple comes first" : "Banana comes first");
Definition and Usage
The compare() function compares two strings, character by character.
It returns 0 if the strings are equal, a negative number if the string comes before the other string, and a positive number if it comes after. The order is based on the ASCII value of each character, so uppercase letters come before lowercase letters.
The compare function is defined in the <string> header file.
Tip: To only check if two strings are equal, you can also use ==, like if (txt1 == txt2).
Syntax
string.compare(str);
string.compare(size_t start, size_t length, str);
Use one of the two forms. The second form only compares a part of the string. The size_t data type is a non-negative integer.
Parameter Values
| Parameter | Description |
|---|---|
| str | Required. The string to compare with. |
| start | Required. The position in the string where the comparison starts. |
| length | Required. The number of characters in the string to compare. |
Technical Details
| Returns: | An int value: 0 if the strings are equal, a negative number if the string comes before str, and a positive number if it comes after. |
|---|
Related Pages
Read more about strings in our String Tutorial.