You need to use runes to prevent corrupting unicode values:
package main
import (
"fmt"
)
func replaceFirstRune(str, replacement string) string {
return string([]rune(str)[:0]) + replacement + string([]rune(str)[1:])
}
func main() {
name := "Hats are great!"
name = replaceFirstRune(name, "C")
fmt.Println(name)
}
Output:
=> Cats are great!
Just like in ruby, this doesnβt cover multi-byte unicode characters. You still need to do a unicode table lookup:
name = "π¨βπ©βπ§βπ¦"
name[0] = "C"
=> "Cβπ©βπ§βπ¦"
println(replaceFirstRune("π¨βπ©βπ§βπ¦", "C"))
=> "Cβπ©βπ§βπ¦"
You can go step more and replace the man with a woman:
println(replaceFirstRune("π¨βπ©βπ§βπ¦", "π©"))
=> "π©βπ©βπ§βπ¦"