且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Golang中替换字符串中的单个字符?

更新时间:2023-02-04 23:23:18

您可以e strings.Replace

You can use strings.Replace.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "a space-separated string"
    str = strings.Replace(str, " ", ",", -1)
    fmt.Println(str)
}

如果需要替换不止一件事情,或者您需要一遍又一遍地进行相同的替换,使用 strings.Replacer

If you need to replace more than one thing, or you'll need to do the same replacement over and over, it might be better to use a strings.Replacer:

package main

import (
    "fmt"
    "strings"
)

// replacer replaces spaces with commas and tabs with commas.
// It's a package-level variable so we can easily reuse it, but
// this program doesn't take advantage of that fact.
var replacer = strings.NewReplacer(" ", ",", "\t", ",")

func main() {
    str := "a space- and\ttab-separated string"
    str = replacer.Replace(str)
    fmt.Println(str)
}

当然,如果您出于编码目的而替换,例如URL编码,那么***使用专门用于该目的的函数,例如为 url.QueryEscape

And of course if you're replacing for the purpose of encoding, such as URL encoding, then it might be better to use a function specifically for that purpose, such as url.QueryEscape