如何在 Go 語言字串中替換字元?


Go 語言的 **strings** 包有一個 **Replace()** 函式,我們可以用它來替換字串中的某些字元。它只替換子字串指定的 "n" 次出現。

除了 **Replace()**,還有一個 **ReplaceAll()** 函式可以將給定子字串的所有出現都替換為新值。

語法

func Replace(s, old, new string, n int) string

其中:

  • **s** 是給定的字串

  • **old** 是我們要替換的字串

  • **new** 是將替換 **old** 字串的字串

  • **n** 表示我們想要在給定字串中替換的字元數。

示例

下面的示例演示瞭如何使用 **Replace()** 函式將子字串替換為新字串。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   s := "Go Programming Language"
   old := "Go"
   newstring := "Golang"
   n := 1

   // Display the Strings
   fmt.Println("Original String: ", s)

   // Using the Replace Function
   testresult := strings.Replace(s, old, newstring, n)

   // Display the Replace Output
   fmt.Println("Replace Go with Golang:", testresult)
}

輸出

它將生成以下輸出:

Original String: Go Programming Language
Replace Go with Golang: Golang Programming Language

示例

在這個例子中,我們將看到如何在特定位置或索引處用新值替換單個字元。

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   // Initializing the Strings
   x := "Replace String Function"
   y := "Go Language"

   // Display the Strings
   fmt.Println("1st String:", x)
   fmt.Println("2nd String:", y)

   // Using the Replace Function
   test1 := strings.Replace(x, "i", "I", 2)
   test2 := strings.Replace(y, "g", "G", -1)

   // Display the Replace Output
   fmt.Println("\n Replace 'i' with 'I' in the 1st String: \n", test1)
   fmt.Println("\n Replace 'g' with 'G' in the 2nd String: \n", test2)
}

輸出

它將生成以下輸出:

1st String: Replace String Function
2nd String: Go Language

Replace 'i' with 'I' in the 1st String:
Replace StrIng FunctIon

Replace 'g' with 'G' in the 2nd String:
Go LanGuaGe

更新於:2022年3月10日

5K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告