Swap Two Strings Using strcpy in C
On this page (7sections)
About this program
This is an example program in c string example programs. Read the concept first: C Strings in C Programming, then study the code and output below.
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
Related Pages
Learn the concept first, then study the code:
- C Programs — Browse all C Programs.
- C Strings in C Programming — Concept — char arrays, strlen, strcpy and strcmp.
- Concatenation of string C Example Program — More in c string example programs.
- Length Of String using strlen() in C Programming Language — More in c string example programs.