OneBite.Dev - Coding blog in a bite size

Swap A String In C++

Code snippet for how to Swap A String In C++ with sample and detail explanation

In this brief article, we’ll break down how to swap a string in C++. Swapping a string simply means exchanging positions of strings: for instance, if we have Strings A and B, after swapping, A becomes B and B becomes A.

Code snippet for Swapping a String in C++

The following is the code to swap two strings in C++. We are going to utilize the inbuilt swap function of the standard library to accomplish this.

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
    string str1, str2;
    
    str1 = "Hello";
    str2 = "World";

    cout << "Before swapping: " << "\n";
    cout << "String 1 is " << str1 << "\n";
    cout << "String 2 is " << str2 << "\n";

    swap(str1, str2);

    cout << "After swapping: " << "\n";
    cout << "String 1 is " << str1 << "\n";
    cout << "String 2 is " << str2 << "\n";

    return 0;
}

We start by defining two strings, str1 and str2, which are initially assigned to “Hello” and “World”, respectively. We then print them out before the swap to evidence the positions at the start.

Following this, we use swap(str1, str2) to interchange the positions of str1 and str2.

Finally, we print the strings again to confirm they’ve swapped places.

Code Explanation for Swapping a String in C++

Let’s have a comprehensive look at the given program.

  1. #include<iostream> and #include<algorithm>: These are headers files, where ‘iostream’ is used for input/output streams and ‘algorithm’ is used to take advantage of built-in function swap().

  2. using namespace std; : It is used because C++ includes many libraries which are kept under the standard namespace.

  3. The main() function: This is the function where our program starts. Here, we define the two strings, str1 and str2, with the values “Hello” and “World”.

  4. Following this, we display the strings before the swap operation.

  5. swap(str1, str2);: This is the actual act of swapping the strings. The swap() function is a built-in function from the C++ Standard Library, which does the job of swapping two values or variables.

  6. The final two lines in main display the two strings after their positions have been swapped.

When you run this program, it will display the strings before and after the swap to allow you a clear comparison. The swapping function can be very useful for operations such as permutations or algorithms which need to rearrange data.

c-plus-plus