How to move all special characters to the beginning of a string in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "unicode"
)

func moveSpecialCharactersToBeginning(s string) string {
    var specials []rune
    var chars []rune

    for _, ch := range s {
        if unicode.IsLetter(ch) || unicode.IsDigit(ch) || unicode.IsSpace(ch) {
            chars = append(chars, ch)
        } else {
            specials = append(specials, ch)
        }
    }

    return string(specials) + string(chars)
}

func main() {
    s := "c++20$c&^java*(rust) php <>/python 3.14.2"
    result := moveSpecialCharactersToBeginning(s)
    
    fmt.Println(result)
}



/*
run:

++$&^*()<>/..c20cjavarust php python 3142

*/

 



answered Dec 12, 2025 by avibootz

Related questions

...