Today I Learned

hashrocket A Hashrocket project

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("๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ", "๐Ÿ‘ฉ"))
=> "๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ"
See More #go TILs