by Dinesh Thakur Category: Puppetting On Strings

The function accepts two strings, str1 and str2, as parameters of type char * and exchanges their contents. Note that the strcpy function is used to copy the strings and a local character array is used to store string strl temporarily. This function can be called from the main function to exchange strings as shown below.

Note that this function has several limitations. First, the function uses a very inefficient approach to exchange strings. Second, the array representing each string should have enough space to accommodate the other string being copied to it and third, the length of the strings being exchanged is limited by the size of the temp array.

#include <stdio.h>
void str_swap(char *str1, char *str2)
   char temp[50];
   strcpy(temp, str1);
   strcpy(str1, str2);
   strcpy(str2, temp);
void main()
   char s1[10] ="Hi";
   char s2[10] ="Bye";
   printf("Before Swaping : s1: %s s2:%s \n", s1, s2);
   str_swap(s1, s2);
   printf("After Swaping s1: %s s2:%s", s1, s2);

     C Program Swap String Using Strcpy Function

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.