C function to Swap strings


The following is an example to swap strings.

Example

 Live Demo

#include<stdio.h>
#include <string.h>
int main() {
   char st1[] = "My 1st string";
   char st2[] = "My 2nd string";
   char swap;
   int i = 0;
   while(st1[i] != '\0') {
      swap = st1[i];
      st1[i] = st2[i];
      st2[i] = swap;
      i++;
   }
   printf("After swapping s1 : %s
", st1);    printf("After swapping s2 : %s
", st2);    return 0; }

Output

After swapping s1 : My 2nd string
After swapping s2 : My 1st string

In the above program, two arrays of char type st1 and st2, a char variable ‘swap’ and an integer variable i are declared. While loop is checking if st1 is not null, swap the values of st1 and st2.

char st1[] = "My 1st string";
char st2[] = "My 2nd string";
char swap;
int i = 0;
while(st1[i] != '\0') {
   swap = st1[i];
   st1[i] = st2[i];
   st2[i] = swap;
   i++;
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements