C program to swap two strings

For swapping two strings from one location to another location, we use strcpy() function.

An array of characters (or) collection of characters is called a string.


Following is the declaration for an array −

char stringname [size];

For example, char string[50]; string of length 50 characters.


  • Using single character constant
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants
char string[10] = "Hello":;


There is a control string "%s" used for accessing the string till it encounters ‘\0’

strcpy ( )

This function is used for copying source string into destination string.

The length of the destination string is greater than or equal to the source string.

The syntax for strcpy() function is as follows −

strcpy (Destination string, Source String);

For example,

char a[50];            char a[50];
strcpy ("Hello",a);    strcpy ( a,"hello");
output: error          output: a= "Hello"


Following is the C program to swap two strings by using strcpy() function −

 Live Demo

   char s1[10],s2[10],s3[10];
   printf("Enter String 1
");    gets(s1);    printf("Enter String 2
");    gets(s2);    printf("Before Swapping
");    printf("String 1 : %s
",s1);    printf("String 2 : %s
",s2);    strcpy(s3,s1);    strcpy(s1,s2);    strcpy(s2,s3);    printf("After Swapping:
");    printf("String 1 : %s
",s1);    printf("String 2 : %s
",s2); }


When the above program is executed, it produces the following result −

Enter String 1
Enter String 2
Before Swapping
String 1: Tutorial
String 2: Point
After Swapping:
String 1: Point
String 2: Tutorial