C program tutorial to swap two strings

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()
    char firstString[100], secondString[100], tempString[100];

    printf("Enter the first string : \n");
    fgets(firstString, 100, stdin);

    printf("Enter the second string :\n");
    fgets(secondString, 100, stdin);

    strcpy(tempString, firstString);
    strcpy(firstString, secondString);
    strcpy(secondString, tempString);

    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 :

  1. Create three character array to store the first string, second string and one more string to store one string while swapping.
  2. Ask the user to enter the first string and store it in firstString variable.
  3. Similarly, ask the user to enter the second string and store it in secondString variable.
  4. Copy the content of firstString variable to the string variable tempString using strcpy function.
  5. Copy the content of secondString to the variable firstString. Now we only need to update the secondString variable.
  6. Copy the content of tempString to the variable secondString. At this position, both strings are swapped.
  7. 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 :
Enter the second string :
After swapping :
First string : world
Second string: hello