C++ Program to Swap two strings


January 31, 2023, Learn eTutorial
1360

This is a C++ program to swap two strings entered by the user.

Swapping of two strings

Swapping refers to interchanging the values between two or more variables. For example, if variable A = 24 and B = 10 then after swapping the values will be A =10 and B = 24. Here two strings are to be swapped. We can use a third variable array called temp array to perform the swapping operation.

How can we write a C++ program to swap two strings?

Here the program asks the user to enter two strings. The value of both the strings gets stored in two character arrays str1[50 ] and str2[50]. Here we are using the library function strcpy() to perform the swapping operation by copying the string. first the string 1 is copied to the temp array variable using strcpy. the copy the string 2 to string 1 and copy the string temp to string 2. finally display string 1 and 2.

Algorithm

Step 1: Call the header file iostream.

Step 2: Call the stdio.h header file

Step 3: Call the string.h header file.

Step 4: Use the namespace std.

Step 5: Open the integer type main function; int main().

Step 6: Declare character type arrays str1[50], str2[50], strtemp[50];

Step 7: Ask the user to enter the first string;

Step 8: Get the first string into the array str1[50];

Step 9: Ask the user to enter the second string;

Step 10: Get the second string into the array str2[50];

Step 11: Display the strings before swapping;

Step 12: Copy the first string into the array strtemp[50];

Step 13: copy the second string into the first array str1[50];

Step 14: Copy the first string from strtemp[50] into the second array str2[50];

Step 15: Display the strings after swapping;

Step 16: Exit;

C++ Source Code

                                          #include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
    char str1[50], str2[50], strtemp[50];
    cout<<"Enter the First String: ";
    cin>>str1;
    cout<<"Enter the Second String: ";
    cin>>str2;
    cout<<"\nString before Swap:\n";
    cout<<"First String = "<<str1<<"\tSecond String = "<<str2;
    strcpy(strtemp, str1);
    strcpy(str1, str2);
    strcpy(str2, strtemp);
    cout<<"\n\nString after Swap:\n";
    cout<<"First String = "<<str1<<"\tSecond String = "<<str2;
    cout<<endl;
    return 0;
}
                                      

OUTPUT

Enter the First String: learnetutorials
Enter the Second String: perfect 
String before Swap:
First String = learnetutorials Second String = perfect

String after Swap:
First String = perfect Second String = learnetutorials