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+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告