C++ String swap
This function is employed to swap the values of two string instances.
Syntax
Exchange the values of two string objects, s1 and s2, by using the following syntax:
s1.swap(s2)
Parameters
It includes a sole parameter, the value of which will be swapped with that of the string object.
Return value
It does not return any value.
Example 1
#include<iostream>
using namespace std;
int main()
{
string r = "10";
string m = "20"
cout<<"Before swap r contains " << r <<"rupees"<<'\n';
cout<<"Before swap m contains " << m <<"rupees"<<'\n';
r.swap(m);
cout<< "After swap r contains " << r<<"rupees"<<'\n';
cout<< "After swap m contains " << m<<"rupees";
return 0;
}
Output:
Before swap r contains 10 rupees
Before swap m contains 20 rupees
After swap r contains 20 rupees
After swap m contains 10 rupees
In this instance, r and m are two string variables holding amounts of 10 and 20 rupees correspondingly. The exchange of their values is achieved through the utilization of the swap function. Following the swap, r now holds 20 rupees while m holds 10 rupees.