Golang Replace() 和 ReplaceAll() 对比
Golang中的 ReplaceAll() 函数将一个给定的子串的所有出现都替换成一个新的值。相反, Replace() 函数只用于用一个新的值替换字符串中的某些字符。它只替换指定的 “n “个出现的子串。
语法
ReplaceAll() 的语法如下-
func ReplaceAll(s, old, new string) string
其中。
- s 是给定的字符串
- old 是我们要替换的字符串,和
- new 是将取代旧字符串的字符串。
例子1
让我们考虑下面的例子 –
package main
import (
"fmt"
"strings"
)
func main() {
// Initializing the Strings
r := "You've Got to Learn Golang String Functions."
// Display the Strings
fmt.Println("Given String: \n", r)
// Using the ReplaceAll Function
testresults := strings.Replace(r, "Go", "ReplaceAll" ,2)
// Display the ReplaceAll Output
fmt.Println("\n After Replacing: \n", testresults)
}
输出
它将产生以下输出 –
Given String:
You've Got to Learn Golang String Functions.
After Replacing:
You've ReplaceAllt to Learn ReplaceAlllang String Functions.
请注意,所有出现的 “Go “都被替换成了 “ReplaceAll”。
例子2
现在,让我们举一个例子来说明 Replace() 函数的使用,这也将突出 Replace() 和 ReplaceAll() 的区别 。
package main
import (
"fmt"
"strings"
)
func main() {
// Initializing the Strings
r := "You've Got to Learn Golang String Functions."
// Display the Strings
fmt.Println("Given String: \n", r)
// Using the Replace Function
testresults := strings.Replace(r, "Go", "ReplaceAll", 1)
// Display the ReplaceAll Output
fmt.Println("\n After Replacing: \n", testresults)
}
输出
在执行时,它将产生以下输出 –
Given String:
You've Got to Learn Golang String Functions.
After Replacing:
You've ReplaceAllt to Learn Golang String Functions.
在这里,你可以注意到只有一个 “Go “的实例被新值 “ReplaceAll “ 所取代 。