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
Read More Articles
- Use of getch(),getche() and getchar() in C
- Switch Case Statement Example Program In C Programming Language
- C Character Set
- Convert a Floating-point value to an Integer in C
- Data Input and Output gets and puts Example Program In C
- Special Operators In C
- Pointer Representation and Pointer Example Programs
- C Data Input and Data Output
- Simple While Loop Example Program In C Programming Language
- Data Output printf and putchar Example Program In C
- C Introduction
- C Operators
- Storage Classes In C
- C Pointers
- File Management
- C Identifiers
- Loop Control Statements
- Hello World - Simple C Program
- C Array
- Single Character Output Function : putchar()
- C Reserve Words
- C Specific Properties and Implementation
- If else Statement Example Program In C Programming Language
- If Statement Example Program In C Programming Language
- Confusing Array in C ( Array Representation and Initialization )