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

1 Answer

0 votes
using System;

public class Program
{
    /// <summary>
    /// Swaps two characters in a character span using the XOR swap algorithm.
    /// </summary>
    /// <remarks>
    /// This method demonstrates XOR swapping for educational purposes.
    /// In production code, standard temporary variable swaps or tuple deconstruction 
    /// (e.g., (text[left], text[right]) = (text[right], text[left])) are preferred for clarity.
    /// </remarks>
    /// <param name="text">The mutable span of characters containing the elements to swap.</param>
    /// <param name="left">Zero-based index of the first character.</param>
    /// <param name="right">Zero-based index of the second character.</param>
    public static void XorSwapCharacters(Span<char> text, int left, int right)
    {
        // Bounds checking and null/empty validation
        if (text.IsEmpty || left < 0 || 
            left >= text.Length || right < 0 || right >= text.Length) {
            return;
        }

        // XOR swap fails if left == right because (x ^ x) evaluates to 0
        if (left == right) {
            return;
        }

        // Cast to char after compound bitwise XOR operation
        text[left] = (char)(text[left] ^ text[right]);
        text[right] = (char)(text[right] ^ text[left]);
        text[left] = (char)(text[left] ^ text[right]);
    }

    public static void Main()
    {
        char[] text = "hello".ToCharArray();

        Console.WriteLine($"Before: {new string(text)}");

        XorSwapCharacters(text, 1, 4);

        Console.WriteLine($"After:  {new string(text)}");
    }
}



/*
run:

Before: hello
After:  holle

*/

 



answered Sep 29 by avibootz
...