函数声明为:
func Replace(s, old, new string, n int) string
官方描述为:
返回将s中前n个不重叠old子串都替换为new的新字符串,如果n<0会替换所有old子串。
package main
import (
"fmt"
"strings"
)
func main() {
s := "123abcabcabc123abcde123cba"
old := "123"
new := "888"
str := strings.Replace(s,old,new,2)
fmt.Println(str)
}
输出:888abcabcabc888abcde123cba
package main
import (
"fmt"
"strings"
)
func main() {
s := "123abcabcabc123abcde123cba"
old := "123"
new := "888"
str := strings.Replace(s,old,new,0)
fmt.Println(str)
}
输出:123abcabcabc123abcde123cba
package main
import (
"fmt"
"strings"
)
func main() {
s := "123abcabcabc123abcde123cba"
old := "123"
new := "888"
str := strings.Replace(s,old,new,-1)
fmt.Println(str)
}
888abcabcabc888abcde888cba