在 Go 语言中,字符串不同于Java、C++、 Python等其他语言。它是一系列可变宽度字符,其中每个字符都由一个或多个使用 UTF-8 编码的字节表示。
在围棋字符串,你才允许更换使用给定函数在给定字符串中的字符。这些函数是在字符串包下定义的,所以你必须在你的程序中导入字符串包才能访问这些函数:
1. 替换:此函数返回包含通过替换旧字符串的元素创建的新字符串的字符串副本。如果给定的旧字符串为空,则它在字符串的开头匹配,并且在每个 UTF-8 序列之后,它会产生 m-rune 字符串 的m+1 替换。如果 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("\nStrings(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("\nStrings(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