The C++ basic_string class compare() member function program example part I
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the basic_string class member function, compare() to compare a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other in C++ programming part I
To show: How to compare a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other in C++ programming using the C++ basic_string class member function, compare() part I
// the C++ compare() member function example part I
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
int str1, str4, str5;
string str2("First");
string str3("First");
//Comparing a string to a string, the character index start from 0
cout<<"str2 string is: "<<str2<<endl;
cout<<"str3 string is: "<<str3<<endl;
// compare str2 and str3 assign the result to str1
cout<<"Operation: str2.compare(str3)"<<endl;
str1 = str2.compare(str3);
if(str1 < 0)
cout<<"The str2 string is less than the str3 string."<<endl;
else if(str1 == 0)
cout<<"The str2 string is equal to the str3 string."<<endl;
else
cout<<"The str2 string is greater than the str3 string."<<endl;
cout<<endl;
// comparing part of a string to another string
string str6("SecondThird");
string str7("Third");
cout<<"str6 string is: "<<str6<<endl;
cout<<"str7 string is: "<<str7<<endl;
cout<<"Operation: str6.compare(6, 5, str7)"<<endl;
str4 = str6.compare(6, 5, str7);
if(str4 < 0)
cout<<"The last 5 characters of the str6 string are less than the str7 string."<<endl;
else if(str4 == 0)
cout<<"The last 5 characters of the str6 string are equal to the str7 string."<<endl;
else
cout<<"The last 5 characters of the str6 string is greater than the str7 string."<<endl;
cout<<endl;
cout<<"Operation: str6.compare(0, 6, str7)"<<endl;
str5 = str6.compare(0, 6, str7);
if(str5 < 0)
cout<<"The first 6 characters of the str6 string are less than the str7 string."<<endl;
else if(str5 == 0)
cout<<"The first 6 characters of the str6 string are equal to the str7 string."<<endl;
else
cout<<"The first 6 characters of the str6 string is greater than the str7 string."<<endl;
return 0;
}
Output example:
str2 string is: First
str3 string is: First
Operation: str2.compare(str3)
The str2 string is equal to the str3 string.
str6 string is: SecondThird
str7 string is: Third
Operation: str6.compare(6, 5, str7)
The last 5 characters of the str6 string are equal to the str7 string.
Operation: str6.compare(0, 6, str7)
The first 6 characters of the str6 string are less than the str7 string.
Press any key to continue . . .