Find the output of C++ Program
May 7, 2013
Printing something without modifying main
May 20, 2013

Function to swap strings in C

Write a C language function that will swap two strings.
1. Swapping the pointers

Sometimes, we can just swap the two pointers pointing to strings as shown in the below code:

void swap(char** ptr1, char** ptr2)
{
    char * temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;
}
int main()
{
    char *str1 = "Ritambhara";
    char *str2 = "0123456789";
    printf("%s : %s\n", str1, str2);
    swap(&str1, &str2);
    printf("%s : %s\n", str1, str2);
}

We need to pass pointer-to-pointer because we want to change the pointer itself (and not data). The output of above program is

Ritambhara : 0123456789
0123456789 : Ritambhara

This code is fast, but problem with the above code is that it cannot swap if strings are stored in character arrays (and not char pointers).

    char str1[] = "Ritambhara";
    char str2[] = "Rawat";
    printf("%s : %s\n", str1, str2);
    swap(&str1, &str2);
    printf("%s : %s\n", str1, str2);

This is because, arrays are not pointers. While they decay to pointers when passed to function, these pointers are not the actual arrays. Since address of array is static, it cannot be changed. If we want to swap two arrays, then we have to swap the data.

2. Swapping the contents

To swap the contents we just need to pass char* to the function

#include
#include
void swap(char* str1, char* str2)
{
    int len = strlen(str1);
    for(int i=0; i<len; i++)
    {
        char temp = str1[i];
        str1[i] = str2[i];
        str2[i] = temp;
    }
}
int main()
{
    char str1[] = "Ritambhara";
    char str2[] = "0123456789";
    printf("%s : %s\n", str1, str2);
    swap(str1, str2);
    printf("%s : %s\n", str1, str2);
}

This code works fine for the above input because both the strings are of equal length. What if the strings to be swapped are of unequal lengths:

    char str1[] = "Ritambhara";
    char str2[] = "Rawat";

This code will crash because it will try to access str2 outside the range inside function swap.

There is no fool proff way of swapping the above two strings, because str2 just does not have enough space to the content of str1.

One case, where Method-1 will do the swap but method-2 will fail is when data pointed to by pointers cannot change. For example:

void swap(char** ptr1, char** ptr2)
{
    char * temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;
}
int main()
{
    const char *str1 = "Ritambhara";
    const char *str2 = "Rawat";
    printf("%s : %s\n", str1, str2);
    swap(&str1, &str2);
    printf("%s : %s\n", str1, str2);
}

Above code will work fine.

Leave a Reply

Your email address will not be published. Required fields are marked *