如何在 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
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP