Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

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
...