How to reverse a string without affecting 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, symbols, and digits 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 := "ab*#cde!@$,fg{}"

	// Convert string to a slice of runes ([]rune) to support safe Unicode handling and index mutation
	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:  ab*#cde!@$,fg{}
Reversed:  gf*#edc!@$,ba{}

*/

 



answered 2 days ago by avibootz

Related questions

...