在 Golang 中可以使用 strings 包中的 Replace 函数来替换字符串中的字符。该函数的语法如下:
func Replace(s, old, new string, n int) string
其中,s 表示原始字符串,old 表示要被替换的字符或子串,new 表示替换后的字符或子串,n 表示最大替换次数。如果 n 小于 0,则表示全部替换。
示例代码:
package main
import (
"fmt"
"strings"
)
func main() {
str := "abc def ghi"
newStr := strings.Replace(str, " ", "-", -1) // 将空格替换成 -
fmt.Println(newStr) // 输出 abc-def-ghi
}