Swap Two Strings in C
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.
#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:
Reverse String in C++
To reverse a string in C++ programming, then ask to the user to enter a string, now make a
variable say temp of char type and start swapping. Place first character of the string in temp and
last character of the string in the first, then place temp in the last and continue, to swap string as
shown in the following program.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[100], temp;
int i=0, j;
cout<<"Enter the String : ";
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
cout<<"Reverse of the String = "<<str;
getch();
}
When the above C++ program is compile and executed, it will produce the following result:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[100], temp;
int i=0, j;
cout<<"Enter the String : ";
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
cout<<"Reverse of the String = "<<str;
getch();
}
When the above C++ program is compile and executed, it will produce the following result:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
char str[100], temp;
int i=0, j;
cout<<"Enter the String : ";
gets(str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
cout<<"Reverse of the String = "<<str;
getch();
}
When the above C++ program is compile and executed, it will produce the following result: