Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ string::swap function is used to exchange the content of one string with the content of another string. Please note that the size of two strings may differ.

Syntax

void swap (string& lhs, string& rhs);
void swap (string& lhs, string& rhs);

Parameters

lhs First string.
rhs Second string.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the string::swap function is used to exchange the content of string MyStr1 with the content of string MyStr2.

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyStr1{"Hello"};
  string MyStr2{"World"};

  cout<<"Before Swapping, The MyStr1 contains:"<<MyStr1<<"\n";
  cout<<"Before Swapping, The MyStr2 contains:"<<MyStr2<<"\n\n";

  swap(MyStr1, MyStr2);

  cout<<"After Swapping, The MyStr1 contains:"<<MyStr1<<"\n";
  cout<<"After Swapping, The MyStr2 contains:"<<MyStr2<<"\n";

  return 0;
}

The output of the above code will be:

Before Swapping, The MyStr1 contains:Hello
Before Swapping, The MyStr2 contains:World

After Swapping, The MyStr1 contains:World
After Swapping, The MyStr2 contains:Hello

❮ C++ - String Functions