实现说明
NewReplacer 一次替换多组子串以函数 main为骨架。
常见问题
「NewReplacer 一次替换多组子串」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
代码示例
package main
import (
"fmt"
"strings"
)
func main() {
// NewReplacer:成对给出 old/new,一次扫描完成全部替换
sanitize := strings.NewReplacer(
"<", "<",
">", ">",
"&", "&",
)
fmt.Println(sanitize.Replace("a < b & c > d"))
// 长度不等也允许:统一破折号、压掉重复空格
normalize := strings.NewReplacer(
"–", "-",
"—", "-",
" ", " ",
)
fmt.Println(normalize.Replace("2026—11—12 draft–v2 notes"))
// Replacer 不可变且并发安全:构造一次,处处复用
fmt.Println(sanitize.Replace("5 > 3 & 1 < 2"))
}