The Compare function is used to compare strings and their substrings, as shown in the following example:
#include <iostream>#include<string>#include<cctype>usingstd::cout; usingStd::endl; usingstd::cin; usingSTD::string; intMainvoid){ stringstr1="Hi,test,hello"; stringStr2="hi,test"; //string comparison if(Str1.compare (STR2) >0) printf ("str1>str2\n"); Else if(Str1.compare (STR2) <0) printf ("str1<str2\n"); Elseprintf ("str1==str2\n"); //str1 substring (starting at index 3, containing 4 characters) compared to str2 if(Str1.compare (3,4, str2) = =0) printf ("str1 the specified substring equals str2\n"); Elseprintf ("the specified substring of the str1 is not equal to str2\n"); //str1 Specifies that the substring is compared to the specified substring of the str2 if(Str1.compare (3,4, STR2,3,4)==0) printf ("the specified substring of the str1 equals the specified substring of str2 \ n"); Elseprintf ("the specified substring of the str1 is not equal to the specified substring of str2 \ n"); //str1 Specifies that substrings are compared to the first n characters of a string if(Str1.compare (0,2,"Hi,hello",2)==0) printf ("STR1 a substring that is equal to the first 2 characters of the specified string \ n"); Elseprintf ("STR1 The specified substring is not equal to the first 2 characters of the specified string \ n"); return 0; }
Execution Result:
32. Use of compare functions in C + +