The compare()
function is a member function of the standard library in the String class. The function compares strings and returns integers that indicate the difference in the strings.
string1.compare(string2)
//or
string1.compare(pos1, len1, string2)
//or
string1.compare(pos1, len1, string2, pos2, length2)
pos1
is the starting position for string1
and len1
dictates the length that would be compared with string2
. pos2
and len2
follow the same conventions.
#include <iostream>#include <string>int main (){std::string str1 ("deep learning");std::string str2 ("machine learning");std::string s3 ("Educative");std::string s4 ("Educative");std::string s5 ("hello!");std::string s6 ("Hello!");std::cout<<str1.compare(str2)<<"\n"; //str1 precedes str2 in sorted orderstd::cout<<s3.compare(s4)<<"\n"; //returns 0std::cout<<s5.compare(s6)<<"\n"; //returns 1 cos lower case > uppercaseif (str1.compare(str2) != 0)std::cout << str1 << " is not equal to " << str2 << '\n';if (str1.compare(5,8,"learning") == 0)std::cout << str1<<" is a type of learning \n";if (str1.compare(5,8,str2,8,8) == 0)std::cout << "Both the strings contain the phrase 'learning' \n";return 0;}
The following code contains 6 strings, compares them, and generates relevant integers or comments.
The first compare system prints a negative number because the string str1
precedes str2
when sorted, i.e., ‘d’ of “deep learning” precedes ‘m’ of “machine learning” in value.
Since the strings str3
and str4
are equal, 0 is generated.
The strings str5
and str6
generate a positive number (a value greater than 0) since the lowercase h
in string str5
has a greater value than the uppercase H
in string str6
.
The first if
statement is executed, since str1
and str2
are not equal.
The second if
statement compares the snippet obtained from index 5 of str1
, spanning over a length of 8 characters and the string specified as the third argument, i.e., “learning”. Since the word “learning” is generated as dictated by the first 2 arguments, the result comes out to be 0 (both strings are equal).
Similarly, the last if
statement is also executed. The first argument specifies the starting index position from str1
, the second argument specifies the spanning length, the third argument specifies the second string for comparison, the fourth argument specifies the starting index for str2
, and the last argument specifies the spanning length of str2
. Since these two substrings result in “learning”, the output comes out to be 0.