Swapping Two String using strcpy In C Programing

Swap Definition

In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory

Using a temporary variable

The simplest and probably most widely used method to swap two variables is to use a third temporary variable:

    temp := x
    x := y
    y := temp

strcpy() function syntax:

char *strcpy(char dest[], const char src[])

Swapping Two String Example Program

/*##Swapping Two Strings*/
/*##String Programs, Datatype Programs, Basic Programs*/
/*##Example*/

#include <stdio.h>
#include <string.h>
#include <malloc.h>

int main()
{
   char string1[100], string2[100], *temp;

   printf("Enter the first string\n");
   gets(string1);

   printf("Enter the second string\n");
   gets(string2);

   printf("\nBefore Swapping\n");
   printf("String One: %s\n",string1);
   printf("String Two: %s\n\n",string2);

   temp = (char*)malloc(100);

   strcpy(temp,string1);
   strcpy(string1,string2);
   strcpy(string2,temp);

   printf("After Swapping\n");
   printf("String One: %s\n",string1);
   printf("String Two: %s\n",string2);

   return 0;
}

Sample Output:

Enter the first string
Add
Enter the second string
Subtract

Before Swapping
String One: Add
String Two: Subtract

After Swapping
String One: Subtract
String Two: Add