replace a character in a string in go

To replace a character in a string in Go, you can use the strings.Replace() function. This function takes in the original string, the substring to replace, the replacement substring, and the number of replacements to make (0 for all occurrences). Here's an example:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world"
    fmt.Println(str) // prints "hello world"

    // replace all occurrences of 'l' with 'x'
    str = strings.Replace(str, "l", "x", -1)
    fmt.Println(str) // prints "hexxo worxd"
}
274 chars
16 lines

In the above code, we first define a string str with the value "hello world". We then use the strings.Replace() function to replace all occurrences of the character 'l' with 'x'. We store the new string back in str and print it out, which gives us "hexxo worxd" as the output.

gistlibby LogSnag