How to implement string swapping in C language?

In C language, string swapping can be achieved by using temporary variables or XOR operation.

Option 1: Use temporary variables.

#include <stdio.h>
#include <string.h>

void swapStrings(char* a, char* b) {
    char temp[100];
    strcpy(temp, a);
    strcpy(a, b);
    strcpy(b, temp);
}

int main() {
    char str1[100] = "Hello";
    char str2[100] = "World";
    
    printf("Before swap: str1 = %s, str2 = %s\n", str1, str2);
    swapStrings(str1, str2);
    printf("After swap: str1 = %s, str2 = %s\n", str1, str2);
    
    return 0;
}

Option two: Utilize XOR operation.

#include <stdio.h>
#include <string.h>

void swapStrings(char* a, char* b) {
    int length = strlen(a);
    
    for (int i = 0; i < length; i++) {
        a[i] = a[i] ^ b[i];
        b[i] = a[i] ^ b[i];
        a[i] = a[i] ^ b[i];
    }
}

int main() {
    char str1[100] = "Hello";
    char str2[100] = "World";
    
    printf("Before swap: str1 = %s, str2 = %s\n", str1, str2);
    swapStrings(str1, str2);
    printf("After swap: str1 = %s, str2 = %s\n", str1, str2);
    
    return 0;
}

Both of these methods can achieve the swapping of strings, so you can choose one method based on your own needs.

bannerAds