C program to swap two strings :
In this tutorial, we will learn how to swap two strings using C programming language. The user will enter both strings and our program will swap these strings and print out the results. Let’s take a look at the program first :
C program :
#include <stdio.h>
#include <string.h>
int main()
{
//1
char firstString[100], secondString[100], tempString[100];
//2
printf("Enter the first string : \n");
fgets(firstString, 100, stdin);
//3
printf("Enter the second string :\n");
fgets(secondString, 100, stdin);
//4
strcpy(tempString, firstString);
//5
strcpy(firstString, secondString);
//6
strcpy(secondString, tempString);
//7
printf("After swapping :\n");
printf("First string : %s", firstString);
printf("Second string: %s", secondString);
}
Explanation :
The commented numbers in the above program denote the step number below :
- Create three character array to store the first string, second string and one more string to store one string while swapping.
- Ask the user to enter the first string and store it in firstString variable.
- Similarly, ask the user to enter the second string and store it in secondString variable.
- Copy the content of firstString variable to the string variable tempString using strcpy function.
- Copy the content of secondString to the variable firstString. Now we only need to update the secondString variable.
- Copy the content of tempString to the variable secondString. At this position, both strings are swapped.
- Print the contents of both string variables.
Sample Output :
Enter the first string :
first string
Enter the second string :
second string
After swapping :
First string : second string
Second string: first string
Enter the first string :
hello
Enter the second string :
world
After swapping :
First string : world
Second string: hello