How to replace a letter at a specific index in a string in Go?

Strings are immutable in Go, you have to convert it to runes then modify it then convert it back to a string.

@chendesheng’s solution is semi-correct, except you can use rune instead of byte, that way it will work on unicode as well.

func replaceAtIndex(in string, r rune, i int) string {
    out := []rune(in)
    out[i] = r
    return string(out)
}

playground

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)