The CompareTo method of the string instance can be used for string comparison.
The Compare and Compare methods are also character strings, but are more powerful.
Basic syntax
Compare has multiple overload functions to list the simplest one.
Public static int Compare (
String strA,
String strB
)
Return Value
Less Than Zero, and less than strB;
Zero, strA is equal to strB;
The value is greater than zero and the value of strA is greater than strB.
Example
Int result = string. Compare ("abc", "ABC ");
Int result = string. Compare ("abc", "ABC", true) // ignore the case sensitivity comparison.
But what we want to talk about is more complex and practical.
# Include <iostream. h>
# Include <string>
Using std: string;
Main (void)
{
String s1 = "abcdefghijk", s2 = "1234567890", s3, s4, s5;
S3 = s1 + s2;
Cout <s3 <endl;
S4 = s3;
If (s4 = s3)
Cout <"s4 = s3 is truen ";
Return (0 );
}
/*
Abcdefghijk1234567890
S4 = s3 is true
*/
Character size comparison
# Include <iostream>
Using std: cout;
Using std: endl;
# Include <string>
Using std: string;
Int main ()
{
String s1 ("AA ");
String s2 ("AAB ");
String s3;
//
Cout <"s1 is" "<s1 <"; s2 is "" <s2
<""; S3 is "" <s3 <'"'
<"NnThe results of comparing s2 and s1 :"
<"Ns2-= s1 yields" <(s2 = s1? "True": "false ")
<"NS2! = S1 yields "<(s2! = S1? "True": "false ")
<"Ns2-> s1 yields" <(s2> s1? "True": "false ")
<"Ns2-< s1 yields" <(s2 <s1? "True": "false ")
<"Ns2-> = s1 yields" <(s2> = s1? "True": "false ")
<"NS2. <= s1 yields" <(s2 <= s1? "True": "false ");
Return 0;
}
/*
S1 is "AA"; s2 is "AAB"; s3 is ""
The results of comparing s2 and s1:
S2 = s1 yields false
S2! = S1 yields true
S2> s1 yields false
S2 <s1 yields true
S2> = s1 yields false
S2 <= s1 yields true
*/
View instances
# Include <iostream>
Using std: cout;
Using std: endl;
# Include <string>
Using std: string;
Int main ()
{
String string1 ("AAAAAAAAAAAAAA ");
String string2 ("bbbbbbbbbbbbbbbb ");
String string3 ("CCCCCCCCCCCCCC ");
String string4 (string2 );
Cout <"string1:" <string1 <"nstring2:" <string2
<"Nstring3:" <string3 <"nstring4:" <string4 <"nn ";
// Comparing string2 and string4
Int result = string4.compare (0, string2.length (), string2 );
If (result = 0)
Cout <"string4.compare (0, string2.length ()," <"string2) = 0" <
Endl;
Else {
If (result> 0)
Cout <"string4.compare (0, string2.length ()," <"string2)> 0" <
Endl;
Else
Cout <"string4.compare (0, string2.length (),"
<"String2) <0" <endl;
}
Return 0;
}
/*
String1: AAAAAAAAAAAAAA
String2: bbbbbbbbbbbbbbbb
String3: CCCCCCCCCCCCCC
String4: bbbbbbbbbbbbbbbb
String4.compare (0, string2.length (), string2) = 0
*/