Loading....
Coupon Accepted Successfully!

 

Comparing And Exchanging

The string class contains functions that enable the programmer to compare and exchange the strings. The related functions are illustrated below with suitable examples:

compare()

The member function compare() is used to compare two strings or sub-strings. It returns 0 when the two strings are similar; otherwise, it returns a non-zero value. It is used in the following formats:

s1.compare (s2);

Here, s1 and s2 are two string objects.

s1.compare (0,4,s2,0,4);

Here, s1 and s2 are string objects. The integer number indicates the sub-string of both the strings that should be compared.

18.22 Write a program to compare two strings. Use compare() function.

#include<iostream>

#include<string>

using namespace std;

int main()

{

string s1 (“Take”);

string s2 (“Taken”);

int d=s1.compare(s2);

cout<<“\n d=”<<d;

d=s1.compare (0,4,s2,0,4);

cout<<“\n d=”<<d;

return 0;

}

OUTPUT

d= -1

d= 0

Explanation: In the above program, s1 and s2 are two string objects that are initialized with the strings “Take” and “Taken”, respectively. The first compare() statement checks the two string objects. It returns –1; that is, the strings are not identical. In the second compare()statement, the element numbers of both the strings that should be compared are sent. Instead of comparing two strings wholly part of one string and whole string of other is compared and tested. In the above program, 0 to 4 elements of both the strings are compared. The functioncompare() returns 0; that is, the two sub-strings are identical.

swap()

The swap() member function is used to exchange the contents of two string objects. It is used in the following format:

s1.swap (s2);

where s1 and s2 are two string objects. The contents of s1 are assigned to s2 and vice versa.

18.23 Write a program to exchange the contents of two string objects. Use the member function swap().

#include<iostream>

#include<string>

using namespace std;

int main()

{

string s1 (“Take”);

string s2 (“Took”);

cout<<“\n s1=”<<s1;

cout<<“\n s2=”<<s2;

cout<<“\n After swap()”;

s1.swap(s2);

cout<<“\n s1=”<<s1;

cout<<“\n s2=”<<s2;

return 0;

}

OUTPUT

s1= Take

s2= Took

After swap()

s1= Took

s2= Take

Explanation: In the above program, string objects s1 and s2 are declared and initialized with “Take” and “Took”, respectively. The swap() function exchanges the contents of s1 and s2; that is, the contents of s1 are assigned to s2 and vice versa. The output of the program is as given above.





Test Your Skills Now!
Take a Quiz now
Reviewer Name