Home Strings Swap strings in C

Swap strings in C

by nikoo28
0 comment 3 minutes read

Question:How will you swap two strings in C?

Let us consider the below program.

#include<stdio.h>
void swap(char *str1, char *str2)
{
	char *temp = str1;
	str1 = str2;
	str2 = temp;
} 
  
int main()
{
	char *str1 = "study";
	char *str2 = "algorithms";
	
	swap(str1, str2);
	
	printf("str1 is %s, str2 is %s", str1, str2);
	
	return 0;
}

Output of the program is str1 is study, str2 is algorithms.
So the above swap() function doesn’t swap strings. The function just changes local pointer variables and the changes are not reflected outside the function.

Let us see the correct ways for swapping strings:

Method 1(Swap Pointers):-

If you are using character pointer for strings (not arrays) then change str1 and str2 to point each other’s data. i.e., swap pointers. In a function, if we want to change a pointer (and obviously we want changes to be reflected outside the function) then we need to pass a pointer to the pointer.

#include<stdio.h>
 
// Swaps strings by swapping pointers
void swap(char **str1_ptr, char **str2_ptr)
{
	char *temp = *str1_ptr;
	*str1_ptr = *str2_ptr;
	*str2_ptr = temp;
} 
  
int main()
{
	char *str1 = "study";
	char *str2 = "algorithms";
	
	swap1(&str1, &str2);
	
	printf("str1 is %s, str2 is %s", str1, str2);
	
	return 0;
}

This method cannot be applied if strings are stored using character arrays.

Method 2(Swap Data) :-

If you are using character arrays to store strings then preferred way is to swap the data of both arrays.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
  
// Swaps strings by swapping data
void swap(char *str1, char *str2)
{
	char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));
	
	//strcpy(a,b) is used to copy String b into String a
	strcpy(temp, str1);
	strcpy(str1, str2);
	strcpy(str2, temp);
	free(temp);
} 
  
int main()
{
	char str1[10] = "study";
	char str2[10] = "algorithms";
	
	swap(str1, str2);
	
	printf("str1 is %s, str2 is %s", str1, str2);
	
	return 0;
}

This method cannot be applied for strings stored in read only block of memory.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More