C++ Standard Library C++ STL Library

C++ <string> - swap() Function



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& other);
void swap (string& other);

Parameters

other Specify string, whose content need to be exchanged with another string.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

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

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string Str1{"Hello"};
  string Str2{"World"};

  cout<<"Before Swapping -"<<"\n";
  cout<<"Str1: "<<Str1<<"\n";
  cout<<"Str2: "<<Str2<<"\n\n";

  Str1.swap(Str2);

  cout<<"After Swapping - "<<"\n";
  cout<<"Str1: "<<Str1<<"\n";
  cout<<"Str2: "<<Str2<<"\n\n";

  return 0;
}

The output of the above code will be:

Before Swapping -
Str1: Hello
Str2: World

After Swapping - 
Str1: World
Str2: Hello

❮ C++ <string> Library

5