go Replace()方法
Replace()语法
func Replace(s, old, new string, n int) string
go源码中对Replace()方法的介绍:
Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.
即,golang中的strings模块的Replace()方法,将字符串s中的old子串用新的子串new替换n次。如果n小于0,new新的子串将替换所有的old子串。
参数
参数 | 描述 |
---|---|
s | go string字符串类型 |
old | 需要被替换的子串。 |
new | 替换old的子串 |
n | 指定new替换old的次数 |
返回值
string字符串,且并不修改原字符串的值。
strings.Replace()实例代码
func main() {
str := "笨鸟工具,x1y1z1.com"
new_str := strings.Replace(str, "1", "2", 2)
fmt.Println(new_str)
fmt.Println(str)
}
运行go文件,得到输出:
笨鸟工具,x2y2z1.com
笨鸟工具,x1y1z1.com