Golang strings.NewReplacer() 函数及示例
strings.NewReplacer() 函数 在 Golang 中,该函数可以从一组旧字符串和对应的新字符串构建一个新的 Replacer。根据它们在目标字符串中的顺序执行替换,不会重叠匹配。旧字符串的比较按参数顺序进行。
语法
func NewReplacer(oldnew ...string) *Replacer
请记住,如果给出的参数数量是奇数,则 NewReplacer 函数将会 panic。
示例 1:
// Golang 中实现 strings.NewReplacer() 函数的示例
package main
import (
"fmt"
"strings"
)
func main() {
r := strings.NewReplacer("<", "<", ">", ">")
fmt.Println(r.Replace("Hey I am <b>GFG</b>!"))
}
输出:
Hey I am <b>GFG</b>!
示例 2:
// Golang 中实现 strings.NewReplacer() 函数的示例
package main
import (
"fmt"
"strings"
)
// 主函数
func main() {
// 调用函数
r := strings.NewReplacer("(", "easy", ")", "tough;")
fmt.Println(r.Replace("The dsa course of geeksforgeeks is ( not )"))
}
输出:
The dsa course of geeksforgeeks is easy not tough;