How to reverse only the alphabetic characters in a string, keeping other characters in place with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "unicode"
)

func reverseOnlyAlphabeticCharacters(s string) string {
    runes := []rune(s)
    i, j := 0, len(runes)-1

    for i < j {
        if !unicode.IsLetter(runes[i]) {
            i++
        } else if !unicode.IsLetter(runes[j]) {
            j--
        } else {
            runes[i], runes[j] = runes[j], runes[i]
            i++
            j--
        }
    }

    return string(runes)
}

func main() {
    s := "a1-bC2-dEf3-ghIj"

    fmt.Println(s)
    fmt.Println(reverseOnlyAlphabeticCharacters(s))
}



/*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz

Related questions

...