Program to Swap two Strings in C

Written by

Pooja Rao

Here, We will write a program in C to swap two strings using two different approaches.

Approach 1: Using inbuilt string functions:

  • This is the easiest technique to implement the above problem statement.
  • We use the inbuilt function strcpy from h header file and swap the text of both strings with the help of a temporarily provisioned array pointer – temp.

Code:

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

int main() { char str1[50], str2[50], *temp;

printf("Enter string 1: "); fgets(str1, 50, stdin); printf("\nEnter string 2: "); fgets(str2, 50, stdin);

printf("\nBefore Swapping\n"); printf("First string: %s\n",str1); printf("Second string: %s\n",str2);

temp = (char*)malloc(100); strcpy(temp,str1);        //swapping values using a temp string pointer. strcpy(str1,str2); strcpy(str2,temp); printf("After Swapping\n"); printf("First string: %s\n",str1); printf("Second string: %s\n",str2);

free(temp);

getch(); return 0;

}

Output:

Enter string 1: Mindblowing!
Enter string 2: Fantastic!
Before Swapping

First string: Mindblowing! Second string: Fantastic!

After Swapping

First string: Fantastic! Second string: Mindblowing!

 

Approach 2: Without using string functions:

  • We will use a temp array here which will hold the characters of the first array on a temporary basis while swapping.
  • str1’s character is held in temp’s ith position, we save str2’s character into str1’s ith position.
  • The character at ith position of str2 is replaced by ith character of temp which holds original data of str1.
  • We continue with the process until the largest string’s null character is encountered.

Code:

#include <stdio.h>

int main() { char temp[100], *str1, *str2; int i, size = 100;

printf("Enter the first string: "); str1 = (char*)malloc(size); getline(&str1, &size, stdin);

printf("\nEnter the second string: "); str2 = (char*)malloc(size); getline(&str2, &size, stdin);

for(i=0; str1[i]!='\0'|| str2[i]!='\0'; i++) { temp[i] = str1[i]; str1[i] = str2[i]; str2[i] = temp[i]; }

printf("\n\nThe strings after swapping:\n\n"); printf("First string:  %s \n", str1); printf("First string:  %s  \n", str2); return 0;

}

Output:

Enter the first string: How are you doing ?
Enter the second string: I am doing good !

The strings after swapping: First string:  I am doing good ! Second string:  How are you doing ?

 

Program to Swap two Strings in C