Loading....
Coupon Accepted Successfully!

 

Relational Operators

Table 18.4 describes various relational operators. These operators can be used with string objects for assignment, comparison, and so on. The following program illustrates the use of relational operators with string objects:

18.5 Write a program to compare two strings using string objects and relational operators.

#include<iostream>

#include<string>

using namespace std;

int main()

{

string s1(“OOP”);

string s2(“OOP”);

if (s1==s2)

cout<<“\n Both the strings are identical”;

else

cout<<“\n Both the strings are different”;

return 0;

}

OUTPUT

Both the strings are identical

Explanation: In the above program, two string objects s1 and s2 are declared. Both the string objects are initialized with the string “OOP.” The if statement checks whether the two strings are identical or different. An appropriate message will be displayed on comparison. Thus, in this program, the two string objects contain the same string, and, hence, it displays the message “Both the strings are identical”.

18.6 Write a program to compare two strings.

#include<iostream>

#include<string>

using namespace std;

int main()

{

string s1(“aaa”);

string s2(“bbb”);

if (s1>s2)

cout<<“\n s1 is greater than s2”;

else

if (s1==s2)

cout<<“\n Both the strings are identical”;

else

cout<<“s2 is greater than s1”;

return 0;

}

OUTPUT

s2 is greater than s1

Explanation: In the above program, two string objects s1 and s2 are declared and initialized with the strings “aaa” and “bbb”, respectively. The nested if..else statement checks the two strings and displays the appropriate massages.

18.7 Write a program to compare two strings using standard function compare().

#include<iostream>

#include<string>

using namespace std;

int main()

{

string s1(“aaa”);

string s2(“bbb”);

int d=s1.compare(s2);

if (d==0)

cout<<“\n Both the strings are identical”;

else if (d>0)

cout<<“s1 is greater than s2”;

else

cout<<“s2 is greater than s1”;

return 0;

}

OUTPUT

s2 is greater than s1

Explanation: In the above program, two string objects s1 and s2 are declared and initialized with the strings “aaa” and “bbb”, respectively. Both the string objects are compared using the compare() function. The return value of the function compare() is stored in the integer variable d. The function compare() returns zero if the two strings are similar; otherwise, a positive value is returned. Using the if..else conditions, appropriate messages are displayed.





Test Your Skills Now!
Take a Quiz now
Reviewer Name