string swap() in C++

swap(): This function swap contents with another string. It exchanges the 

contents of this string with that of __s in constant time. 

Parameters: One parameter is required for this function.

 __s – String to swap with. 

This function is available in the below file.

File: basic_string.tcc

Syntax:

str.swap(__s)

For Example:

str = "abc",  __s  ="defg"

str.swap(__s) = > str = "defg", __s = "abc"

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str1 = "abc";
    string str2 = "defg";

    cout << str1 << " " << str2 << "\n";
    str1.swap(str2);

    cout << str1 << " " << str2 << "\n";

    return 0;
}


No comments:

Post a Comment