How to reverse a slice of characters without affecting the special characters in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"unicode"
)

/**
 * Reverses only the alphabetic characters in a rune slice in-place,
 * leaving special characters, digits, and spaces in their original positions.
 * 
 * @param chars A mutable slice of runes (characters) to modify.
 */
func reverseOnlyLetters(chars []rune) {
	if len(chars) == 0 {
		return // Guard against empty slices
	}

	left := 0
	right := len(chars) - 1

	// Use a two-pointer approach moving inward from both ends
	for left < right {
		// Advance left pointer until it points to an alphabetic character
		for left < right && !unicode.IsLetter(chars[left]) {
			left++
		}
		
		// Move right pointer backward until it points to an alphabetic character
		for left < right && !unicode.IsLetter(chars[right]) {
			right--
		}

		// Swap the valid letters found at both pointers using Go's multi-assignment
		if left < right {
			chars[left], chars[right] = chars[right], chars[left]
			left++
			right--
		}
	}
}

func main() {
	// Input string specified
	input := "a#b$%c&*(def!"

	// Convert string to a slice of runes ([]rune) to support safe Unicode character handling
	chars := []rune(input)

	fmt.Printf("Original: %s\n", string(chars))

	// Apply the reversal function in-place
	reverseOnlyLetters(chars)

	// Convert the modified rune slice back to a string for display
	fmt.Printf("Reversed: %s\n", string(chars))
}


/*
run:

Original: a#b$%c&*(def!
Reversed: f#e$%d&*(cba!

*/

 



answered 6 days ago by avibootz

Related questions

...