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& 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 example below, the 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";

  swap(str1, 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