C Program to Swap two equal Strings

C-Programs C-String-Programs

In this article, we are going to learn how to swap two strings in the C language. Here we are going to take two strings in which one will hold the string text “a” and second will hold the string text “b”. Our goal is to swap the text among both the strings. Here we are going to take two strings and we will iterate over those strings to swap them character by character. let us see this code example to understand.

Note– This program will work for two equal size strings Because this is character by character swapping logic.

C Program to Swap two equal Strings


#include <stdio.h>

int main() 
{
   char str1[] = "DevEnum";     
   char str2[] = "Program";     
   char tmp;

   int i = 0;

   printf("The contents of the Strings are : \n");
   printf("String1 Holds : %s \n", str1);
   printf("String2 Holds : %s \n", str2);

   while(str1[i] != '
#include <stdio.h>

int main() 
{
   char str1[] = "DevEnum";     
   char str2[] = "Program";     
   char tmp;

   int i = 0;

   printf("The contents of the Strings are : \n");
   printf("String1 Holds : %s \n", str1);
   printf("String2 Holds : %s \n", str2);

   while(str1[i] != '\0') 
  {
      tmp = str1[i];
      str1[i] = str2[i];
      str2[i] = tmp;
      i++;
   }

   printf("The contents of the Strings After Swapping are : \n");
   printf("String1 Holds : %s \n", str1);
   printf("String2 Holds : %s \n", str2);

   return 0;
}
') { tmp = str1[i]; str1[i] = str2[i]; str2[i] = tmp; i++; } printf("The contents of the Strings After Swapping are : \n"); printf("String1 Holds : %s \n", str1); printf("String2 Holds : %s \n", str2); return 0; }

Output

The contents of the Strings are : 
String1 Holds : DevEnum 
String2 Holds : Program 
The contents of the Strings After Swapping are : 
String1 Holds : Program 
String2 Holds : DevEnum