codescracker


c++

C++ Program to Swap Two Strings



« Previous Program Next Program »


Swap Two Strings in C++

To swap two string in C++ Programming, you have to first ask to the user to enter the two string, and store both the string in variables say str1 (string 1) and str2 (string 2). Now, to swap two string, first make a variable say temp of the same type. And place the first string in the temp, then place the second string in the first, then place the temp string in the second. And at last, after swapping both the string, print it on the output screen as shown here in the following program.

C++ Programming Code to Swap Two Strings

Following C++ program ask to the user to enter the two strings (you can enter any two name or two word), to swap the string, then display the result after the swapping the strings:

/* C++ Program - Swap Two Strings */
		
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
  clrscr();
  int i=0, j=0, k=0;
  char str1[20], str2[20], temp[20];
  cout<<"Enter the First String : ";
  gets(str1);
  cout<<"Enter the Second String : ";
  gets(str2);
  cout<<"Strings before swapping are :\n";
  cout<<"String 1 = "<<str1<<"\n";
  cout<<"String 2 = "<<str2<<"\n";
  while(str1[i]!='\0')
  {
	temp[j]=str1[i];
	i++;
	j++;
  }
  temp[j]='\0';
  i=0, j=0;
  while(str2[i]!='\0')
  {
	str1[j]=str2[i];
	i++;
	j++;
  }
  str1[j]='\0';
  i=0, j=0;
  while(temp[i]!='\0')
  {
	str2[j]=temp[i];
	i++;
	j++;
  }
  str2[j]='\0';
  cout<<"Strings after swapping : \n";
  cout<<"String 1 = "<<str1<<"\n";
  cout<<"String 2 = "<<str2<<"\n";
  getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program swap two strings

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test