type Replacer struct {
Replace(s string) string
WriteString(w io.Writer, s string) (n int, err error)
}
------------------------------------------------------------
// NewReplacer 通过“替换列表”创建一个 Replacer 对象。
// 按照“替换列表”中的顺序进行替换,只替换非重叠部分。
// 如果参数的个数不是偶数,则抛出异常。
// 如果在“替换列表”中有相同的“查找项”,则后面重复的“查找项”会被忽略
func NewReplacer(oldnew ...string) *Replacer
------------------------------------------------------------
// Replace 返回对 s 进行“查找和替换”后的结果
// Replace 使用的是 Boyer-Moore 算法,速度很快
func (r *Replacer) Replace(s string) stringfunc main() {
srp := strings.NewReplacer("Hello", "你好", "World", "世界", "!", "!")
s := "Hello World!Hello World!hello world!"
rst := srp.Replace(s)
fmt.Print(rst) // 你好 世界!你好 世界!hello world!
}
<span style="color:#FF0000;">注:这两种写法均可.</span>
func main() {wl := []string{"Hello", "Hi", "Hello", "你好"}
srp := strings.NewReplacer(wl...)
s := "Hello World! Hello World! hello world!"
rst := srp.Replace(s)
fmt.Print(rst) // Hi World! Hi World! hello world!
}
------------------------------------------------------------
// WriteString 对 s 进行“查找和替换”,然后将结果写入 w 中
func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)func main() {
wl := []string{"Hello", "你好", "World", "世界", "!", "!"}
srp := strings.NewReplacer(wl...)
s := "Hello World!Hello World!hello world!"
srp.WriteString(os.Stdout, s)
// 你好 世界!你好 世界!hello world!
}









