مقایسه رشته ها
یک شنبه 7 آذر 1389 1:19 AM
1 // Demonstrating string comparison capabilities.
2 #include <iostream>
3 using std::cout;
4 using std::endl;
5
6 #include <string>
7 using std::string;
8
9 int main()
10 {
11 string string1( "Testing the comparison functions." );
12 string string2( "Hello" );
13 string string3( "stinger" );
14 string string4( string2 );
15
16 cout << "string1: " << string1 << "\nstring2: " << string2
17 << "\nstring3: " << string3 << "\nstring4:" << string4 << "\n\n";
18
19 // comparing string1 and string4
20 if ( string1 == string4 )
21 cout << "string1 == string4\n";
22 else // string1 != string4
23 {
24 if ( string1 > string4 )
25 cout << "string1 > string4\n";
26 else // string1 < string4
27 cout << "string1 < string4\n";
28 } // end else
29
30 // comparing string1 and string2
31 int result = string1.compare( string2 );
32
33 if ( result == 0 )
34 cout << "string1.compare( string2 ) == 0\n";
35 else // result != 0
36 {
37 if ( result > 0 )
38 cout << "string1.compare( string2 ) > 0\n";
39 else // result < 0
40 cout << "string1.compare( string2 ) < 0\n";
41 } // end else
42
43 // comparing string1 (elements 2-5) and string3 (elements 0-5)
44 result = string1.compare( 2, 5, string3, 0, 5 );
45
46 if ( result == 0 )
47 cout << "string1.compare( 2, 5, string3, 0, 5 ) == 0\n";
48 else // result != 0
49 {
50 if ( result > 0 )
51 cout << "string1.compare( 2, 5, string3, 0, 5 ) > 0\n";
52 else // result < 0
53 cout << "string1.compare( 2, 5, string3, 0, 5 ) < 0\n";
54 } // end else
55
56 // comparing string2 and string4
57 result = string4.compare( 0, string2.length(), string2 );
58
59 if ( result == 0 )
60 cout << "string4.compare( 0, string2.length(), "
61 << "string2 ) == 0" << endl;
62 else // result != 0
63 {
64 if ( result > 0 )
65 cout << "string4.compare( 0, string2.length(), "
66 << "string2 ) > 0" << endl;
67 else // result < 0
68 cout << "string4.compare( 0, string2.length(), "
69 << "string2 ) < 0" << endl;
70 } // end else
71
72 // comparing string2 and string4
73 result = string2.compare( 0, 3, string4 );
74
75 if ( result == 0 )
76 cout << "string2.compare( 0, 3, string4 ) == 0" << endl;
77 else // result != 0
78 {
79 if ( result > 0 )
80 cout << "string2.compare( 0, 3, string4 ) > 0" << endl;
81 else // result < 0
82 cout << "string2.compare( 0, 3, string4 ) < 0" << endl;
83 } // end else
84
85 return 0;
86 } // end main
string1: Testing the comparison functions. string2: Hello string3: stinger string4: Hello string1> string4 string1.compare( string2 ) > 0 string1.compare( 2, 5, string3, 0, 5 ) == 0 string4.compare( 0, string2.length(), string2 ) == 0 string2.compare( 0, 3, string4 ) < 0 string1.compare( string2 ) >0 |