codescracker


c

C Program to Swap Two Strings



« Previous Program Next Program »


Swap Two String in C

To swap two string in C programming, you have to first ask to the user to enter the two string, then make a temp variable of the same type. Now place the first string in the temp, then place the second string in the first, then place the temp string in the second.

C Programming Code to Swap Two Strings

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

/* C Program - Swap Two Strings */
		
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
  clrscr();
  int i=0, j=0, k=0;
  char str1[20], str2[20], temp[20];
  printf("Enter the First String : ");
  gets(str1);
  printf("Enter the Second String : ");
  gets(str2);
  printf("Strings before swapping are :\n");
  printf("String 1 = %s\n",str1);
  printf("String 2 = %s\n",str2);
  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';
  printf("Strings after swapping : \n");
  printf("String 1 = %s\n",str1);
  printf("String 2 = %s\n",str2);
  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 Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test