Swap two strings in c is a program to swap or exchange the value present in two strings using string functions in c.

String in c
String in c is a collection of characters. And it ends with the null character.
In c string has different string functions such as strcmp, strrev, strlen, strcpy etc.
To swap the two string using string functions we use strcpy string function in c

String copy in c
To copy one string to another string in c the string class provided one function strcpy () using this function we copy one string to another string.

The syntax for strcpy c
strcpy(destination string, source string);
This function returns a pointer to the destination string.

Example swap two strings
string 1 = define , string2 = loop, temp
1. Copy string1 to temp
strcpy (temp, string 1)
Now string 1 is copied to temp
temp = define
2. Copy string2 to string1
strcpy (string 1, string 2)
Now string 2 is copied to string 1
string 1 = loop
3. Copy temp to string 2
strcpy (string 2, temp)
Now temp is copied to string 2
string 2 = define
Swapped values
string 1= loop and string2 = define

Algorithm to swap two strings in c

  1. Declare variable, str1, str2,t
  2. Take two string input from user
  3. Swap two strings using strcpy
    strcpy(str1, str2)
    strcpy(str2, t)
  4. Print swapped strings. str1, str2

C program to swap two strings in c





char s1[10],s2[10],s3[10];

printf("Enter String 1\n");


printf("Enter String 2\n");


printf("Before Swapping\n");

printf("String 1 : %s\n",s1);
printf("String 2 : %s\n",s2);




printf("After Swapping:\n");

printf("String 1 : %s\n",s1);

printf("String 2 : %s\n",s2);


Output :

Swap two strings in c

Write A Comment