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*/

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

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

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

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

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

   temp = (char*)malloc(100);


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

   return 0;

Sample Output:

Enter the first string
Enter the second string

Before Swapping
String One: Add
String Two: Subtract

After Swapping
String One: Subtract
String Two: Add