07 Oct 2021   go


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("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", "πŸ‘©"))
=> "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦"
πŸ„