Go语言中Replace()与ReplaceAll()的比较


Go语言中的**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”**替换了。

更新于:2022年3月10日

16K+ 浏览量

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.