How to use XOR to swap two characters in a string in C

1 Answer

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

/**
 * @brief Swap two characters in a string using XOR operations.
 *
 * This function demonstrates the XOR swap algorithm for educational
 * purposes. In production code, using a temporary variable is usually
 * preferred for readability and maintainability.
 *
 * @param str String containing the characters to swap.
 * @param left Index of the first character.
 * @param right Index of the second character.
 */
void xor_swap_chars(char *str, size_t left, size_t right)
{
    if (str == NULL) {
        return;
    }

    size_t len = strlen(str);
    if (len == 0 || left >= len || right >= len) {
        return;
    }

    /* Prevent when both indices are the same. */
    if (left == right) {
        return;
    }

    str[left] ^= str[right];
    str[right] ^= str[left];
    str[left] ^= str[right];
}

int main(void)
{
    char text[] = "hello";

    printf("Before: %s\n", text);

    xor_swap_chars(text, 1, 4);

    printf("After:  %s\n", text);

    return 0;
}


/*
run:

Before: hello
After:  holle

*/

 



answered Sep 29 by avibootz
...