Golang 如何替换字符串
在Go语言中,字符串与Java、C++、Python等其他语言不同,它是一个变宽的字符序列,每个字符都使用UTF-8编码的一个或多个字节表示。在Go中的字符串中,您可以使用给定的函数替换给定字符串中的字符,这些函数在strings包中定义,因此您必须在程序中导入strings包才能访问这些函数:
1. Replace: 此函数返回一个包含新字符串的字符串的副本,该新字符串由旧字符串中的元素替换而成。如果给定的旧字符串为空,则它匹配字符串的开头,并且在每个UTF-8序列后,它会产生最多m + 1个替换,其中m为rune字符串。如果n的值小于零,则此函数可以替换给定字符串中的任意数量的元素(无限制)。
语法:
func Replace(str, oldstr, newstr string, m int) string
这里, str 是原始字符串, oldstr 是要替换的字符串, newstr 是替换 oldstr 的新字符串,而 n 是旧字符串要替换的次数。
例子:
// Go程序演示如何替换给定字符串中的字符
package main
import (
"fmt"
"strings"
)
// Main函数
func main() {
// 创建和初始化字符串
str1 := "Welcome to Geeks for Geeks"
str2 := "This is the article of the Go string is a replacement"
fmt.Println("原始字符串")
fmt.Println("字符串1:", str1)
fmt.Println("字符串2:", str2)
// 替换字符串
// 使用Replace()函数
res1 := strings.Replace(str1, "e", "E", 3)
res2 := strings.Replace(str2, "is", "IS", -2)
res3 := strings.Replace(str1, "Geeks", "GFG", 0)
// 显示结果
fmt.Println("\n字符串(替换后)")
fmt.Println("结果1:", res1)
fmt.Println("结果2:", res2)
fmt.Println("结果3:", res3)
}
输出:
原始字符串
字符串1:Welcome to Geeks for Geeks
字符串2:This is the article of the Go string is a replacement
字符串(替换后)
结果1:WElcomE to GEeks for Geeks
结果2:ThIS IS the article of the Go string IS a replacement
结果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程序用于说明如何
// 替换给定字符串中的字符
package main
import (
"fmt"
"strings"
)
// 主函数
func main() {
// 创建并初始化字符串变量
str1 := "欢迎来到Geeks for Geeks"
str2 := "这是关于Go字符串替换的文章"
fmt.Println("原始字符串")
fmt.Println("字符串1: ", str1)
fmt.Println("字符串2: ", str2)
// 替换字符串
// 使用ReplaceAll()函数
res1 := strings.ReplaceAll(str1, "Geeks", "GFG")
res2 := strings.ReplaceAll(str2, "the", "THE")
// 显示结果
fmt.Println("\n替换后的字符串")
fmt.Println("结果1: ", res1)
fmt.Println("结果2: ", res2)
}
// Go程序用于说明如何
// 替换给定字符串中的字符
package main
import (
"fmt"
"strings"
)
// 主函数
func main() {
// 创建并初始化字符串变量
str1 := "欢迎来到Geeks for Geeks"
str2 := "这是关于Go字符串替换的文章"
fmt.Println("原始字符串")
fmt.Println("字符串1: ", str1)
fmt.Println("字符串2: ", str2)
// 替换字符串
// 使用ReplaceAll()函数
res1 := strings.ReplaceAll(str1, "Geeks", "GFG")
res2 := strings.ReplaceAll(str2, "the", "THE")
// 显示结果
fmt.Println("\n替换后的字符串")
fmt.Println("结果1: ", res1)
fmt.Println("结果2: ", res2)
}
输出:
原始字符串
字符串1: 欢迎来到Geeks for Geeks
字符串2: 这是关于Go字符串替换的文章
替换后的字符串
结果1: 欢迎来到GFG for GFG
结果2: 这是THE文章的Go字符串替换