在 Go 语言中,字符串 不同于其他语言,例如 Java, C++ , Python,等等。它是一系列可变宽度字符,其中每个字符都使用 UTF-8 编码由一个或多个字节表示。在 Go 字符串中,您可以使用给定函数替换给定字符串中的字符。这些函数是在strings包下定义的,所以你必须在程序中导入strings包才能访问这些函数:

1。替换:此函数返回包含通过替换旧字符串中的元素创建的新字符串的字符串的副本。如果给定的旧字符串为空,则它在字符串的开头匹配,并且在每个 UTF-8 序列之后,它最多产生 m + 1 个替换 m-rune 字符串。如果 n 的值小于零,那么这个函数可以替换给定字符串中任意数量的元素(没有任何限制)。

语法:

func Replace(str, oldstr, newstr string, m int) string

这里str是原始字符串,oldstr是要替换的字符串,newstr是替换oldstr的新字符串,n是oldstr替换的次数。

例子:

// Go program to illustrate how to
// replace characters in the given string
package main
  import (
    "fmt"
    "strings"
)
  // Main function
func main() {
      // Creating and initializing strings
    str1 := "Welcome to Geeks for Geeks"
    str2 := "This is the article of the Go string is a replacement"
      fmt.Println("Original strings")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
      // Replacing strings
    // Using Replace() function
    res1 := strings.Replace(str1, "e", "E", 3)
    res2 := strings.Replace(str2, "is", "IS", -2)
    res3 := strings.Replace(str1, "Geeks", "GFG", 0)
      // Displaying the result
    fmt.Println("
Strings(After replacement)")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
}

输出:

Original strings
String 1: Welcome to Geeks for Geeks
String 2: This is the article of the Go string is a replacement

Strings(After replacement)
Result 1: WElcomE to GEeks for Geeks
Result 2: ThIS IS the article of the Go string IS a replacement
Result 3: Welcome to Geeks for Geeks

2。 ReplaceAll:此函数用于将所有旧字符串替换为新字符串。如果给定的旧字符串是空的,那么它会在字符串的开头匹配,并且在每个 UTF-8 序列之后,它会产生最多 M + 1 个 M-rune 字符串的替换。

语法:

func ReplaceAll(str, oldstr, newstr string) string

这里str是原字符串,oldstr是要替换的字符串,newstr是替换oldstr的新字符串。让我们借助一个例子来讨论这个概念:

例子:

// Go program to illustrate how to
// replace characters in the given string
package main
  import (
    "fmt"
    "strings"
)
  // Main function
func main() {
      // Creating and initializing strings
    str1 := "Welcome to Geeks for Geeks"
    str2 := "This is the is the article of the Go string is a replacement"
      fmt.Println("Original strings")
    fmt.Println("String 1: ", str1)
    fmt.Println("String 2: ", str2)
      // Replacing strings
    //  Using ReplaceAll() function
    res1 := strings.ReplaceAll(str1, "Geeks", "GFG")
    res2 := strings.ReplaceAll(str2, "the", "THE")
      // Displaying the result
    fmt.Println("
Strings(After replacement)")
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
  }

输出:

Original strings
String 1: Welcome to Geeks for Geeks
String 2: This is the is the article of the Go string is a replacement

Strings(After replacement)
Result 1: Welcome to GFG for GFG
Result 2: This is THE is THE article of THE Go string is a replacement