Golang 如何替换字符串中的字符

Golang 如何替换字符串中的字符

Golang的 字符串 包有一个 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程