COMPARE()
This member of the std::string class is used to lexicographically (dictionary order) compare the contents of two strings and returns an integer indicating their relative order. Specifically, it returns 0 if the strings are equal, a negative value if the calling string is less than the argument string, and a positive value if it is greater. This function can compare the entire string or specified substrings, providing a flexible way to check equality or ordering without directly using relational operators. It is widely used in sorting, searching, and string validation operations.
string1.compare(string2);
* string1 is the caller, and string2 is the string it is being compared to.
* returns 0 if strings are equal, < 0 if the caller is less, and > 0 if the caller
is greater.
* the comparison is based on ASCII values of characters from left to right; the first
unmatched character decides the result.
- ASCII (American Standard Code for Information Interchange) assigns a numeric
value to each character (e.g., 'A' = 65, 'a' = 97).
#include <iostream>
using namespace std;
int main()
{
string a = "mango"; // First string
string b = "manga"; // Second string to compare
// Compare the two strings lexicographically
// They match until the last character: 'o' in "mango" vs 'a' in "manga"
// Since 'o' > 'a' in ASCII, the result is positive
int result = a.compare(b); // Returns 14 ('o' - 'a' = 111 - 97)
// Show the comparison result
cout << "Comparison result: " << result << endl; // Output: 14
return 0;
}
Last updated