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,406 questions

56,397 answers

573 users

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

1 Answer

0 votes
package main

import (
	"fmt"
)

// XORSwapCharacters swaps two characters in a byte slice using the XOR swap algorithm.
//
// This function demonstrates XOR swapping for educational purposes.
// In production Go code, tuple assignment (b[left], b[right] = b[right], b[left])
// is strongly preferred for readability and optimizer friendliness.
//
// Note: This implementation assumes ASCII/single-byte characters. For multi-byte
// UTF-8 strings, use a []rune slice instead.
func XORSwapCharacters(b []byte, left, right int) {
	// Bounds checking and empty slice protection
	if len(b) == 0 || left < 0 || left >= len(b) || right < 0 || right >= len(b) {
		return
	}

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

	b[left] ^= b[right]
	b[right] ^= b[left]
	b[left] ^= b[right]
}

func main() {
	original := "hello"
	textBytes := []byte(original)

	fmt.Printf("Before: %s\n", string(textBytes))

	XORSwapCharacters(textBytes, 1, 4)

	fmt.Printf("After:  %s\n", string(textBytes))
}


/*
run:

Before: hello
After:  holle

*/

 



answered 5 days ago by avibootz
...