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

1 Answer

0 votes
/**
 * Swaps two characters in a [CharArray] in-place using the XOR swap algorithm.
 *
 * **Note:** This function demonstrates bitwise XOR swapping for educational purposes.
 * In production Kotlin code, using a temporary variable or array destructuring
 * is strongly preferred for clarity, readability, and optimizer performance.
 *
 * @param text The mutable array of characters containing elements to swap.
 * @param left Zero-based index of the first character.
 * @param right Zero-based index of the second character.
 */
fun xorSwapCharacters(text: CharArray, left: Int, right: Int) {
    // Bounds checking and empty array validation
    if (text.isEmpty() || left < 0 || left >= text.size || right < 0 || right >= text.size) {
        return
    }

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

    // Convert chars to UTF-16 code points, perform bitwise xor, and cast back to Char
    text[left] = (text[left].code xor text[right].code).toChar()
    text[right] = (text[right].code xor text[left].code).toChar()
    text[left] = (text[left].code xor text[right].code).toChar()
}

fun main() {
    val original = "hello"
    val textArray = original.toCharArray()

    println("Before: ${String(textArray)}")

    xorSwapCharacters(textArray, 1, 4)

    val result = String(textArray)
    println("After:  $result")
}


/*
run:

Before: hello
After:  holle

*/

 



answered Sep 30 by avibootz
...