C++ String Compare: Purpose & Usage

The compare function in C++ is used to compare the size relationship between two strings. It returns an integer value indicating the comparison result of the two strings.

Specifically, return 0 if the strings are equal, a negative number if the first string is less than the second in lexicographical order, and a positive number if the first string is greater than the second.

For example:

std::string str1 = "hello";
std::string str2 = "world";

int result = str1.compare(str2);

if(result < 0)
    std::cout << "str1小于str2" << std::endl;
else if(result > 0)
    std::cout << "str1大于str2" << std::endl;
else
    std::cout << "str1等于str2" << std::endl;

This code will output “str1 is less than str2” because in dictionary order, “hello” is smaller than “world”.

bannerAds