Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C function to Swap strings
In C programming, swapping strings involves exchanging the contents of two string variables. This can be achieved through character-by-character swapping or by swapping string pointers.
Syntax
// Character-by-character swapping void swapStrings(char str1[], char str2[]); // Pointer swapping void swapPointers(char **str1, char **str2);
Method 1: Character-by-Character Swapping
This method swaps each character of the strings individually −
#include <stdio.h>
#include <string.h>
int main() {
char st1[] = "My 1st string";
char st2[] = "My 2nd string";
char swap;
int i = 0;
printf("Before swapping:<br>");
printf("st1: %s<br>", st1);
printf("st2: %s<br>", st2);
// Find the maximum length to ensure complete swap
int len1 = strlen(st1);
int len2 = strlen(st2);
int maxLen = (len1 > len2) ? len1 : len2;
// Swap characters
for(i = 0; i < maxLen; i++) {
swap = st1[i];
st1[i] = st2[i];
st2[i] = swap;
}
printf("\nAfter swapping:<br>");
printf("st1: %s<br>", st1);
printf("st2: %s<br>", st2);
return 0;
}
Before swapping: st1: My 1st string st2: My 2nd string After swapping: st1: My 2nd string st2: My 1st string
Method 2: Using Temporary String
This approach uses a temporary array to store one string during the swap −
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char temp[100];
printf("Before swapping:<br>");
printf("str1: %s<br>", str1);
printf("str2: %s<br>", str2);
// Copy str1 to temp, str2 to str1, temp to str2
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
printf("\nAfter swapping:<br>");
printf("str1: %s<br>", str1);
printf("str2: %s<br>", str2);
return 0;
}
Before swapping: str1: Hello str2: World After swapping: str1: World str2: Hello
Key Points
- Character-by-character method works in-place but requires strings of similar length for complete swap.
- Temporary string method is safer and handles strings of different lengths correctly.
- Always ensure sufficient buffer size when using
strcpy()to avoid buffer overflow.
Conclusion
String swapping in C can be accomplished through character swapping or using temporary storage. The strcpy() approach is generally preferred as it handles strings of different lengths safely.
Advertisements
