Replace first letter of string
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("๐จโ๐ฉโ๐งโ๐ฆ", "๐ฉ"))
=> "๐ฉโ๐ฉโ๐งโ๐ฆ"
Tweet