How to use XOR to swap two characters in a string in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ''' <summary>
    ''' Swaps two characters in a Char array using the XOR swap algorithm.
    ''' </summary>
    ''' <remarks>
    ''' This procedure demonstrates XOR swapping for educational purposes.
    ''' In production code, using a temporary variable is preferred for clarity
    ''' and compiler optimization.
    ''' </remarks>
    ''' <param name="text">The character array containing the characters 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 Sub XorSwapCharacters(ByRef text As Char(), ByVal left As Integer, ByVal right As Integer)
        ' Bounds checking and null validation
        If text Is Nothing OrElse text.Length = 0 OrElse
           left < 0 OrElse left >= text.Length OrElse
           right < 0 OrElse right >= text.Length Then
            Return
        End If

        ' XOR swap fails if left = right because (x Xor x) evaluates to 0
        If left = right Then
            Return
        End If

        ' Convert characters to UTF-16 integer codes, perform bitwise XOR, and cast back
        text(left) = Convert.ToChar(Convert.ToInt32(text(left)) Xor Convert.ToInt32(text(right)))
        text(right) = Convert.ToChar(Convert.ToInt32(text(right)) Xor Convert.ToInt32(text(left)))
        text(left) = Convert.ToChar(Convert.ToInt32(text(left)) Xor Convert.ToInt32(text(right)))
    End Sub

    Sub Main()
        Dim original As String = "hello"
        Dim text As Char() = original.ToCharArray()

        Console.WriteLine("Before: " & New String(text))

        XorSwapCharacters(text, 1, 4)

        Console.WriteLine("After:  " & New String(text))
    End Sub

End Module
				
	
					
'
' run:
'
' Before: hello
' After:  holle
'
'
					

 



answered Sep 29 by avibootz
...