String Swap Function - C++ Programming Tutorial
C++ Course / Strings / String Swap Function

String Swap Function

BLUF: Mastering String Swap Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: String Swap Function

C++ is renowned for its efficiency. Learn how String Swap Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

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

Example

#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:

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience