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;

  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