Go语言字符串全部替换

Go语言字符串全部替换教程

在开发过程中,有时候我们需要将一个 字符串 中特定的字符串全部替换成新的字符串的需求,在 Go 语言 中,我们可以通过 strings.Replace() 函数最后一次参数传递 -1 来实现。

但 Golang 给我们提供了一个更方便的 函数,即 strings.ReplaceAll() 函数。

strings.ReplaceAll()函数

语法

func ReplaceAll(s, old, new string) string

参数

参数 描述
s 要替换的整个字符串。
old 要替换的字符串。
new 替换成什么字符串。

返回值

返回替换后的字符串。

说明

将字符串 s 中的 old 字符串全部替换成 new 字符串,返回替换后的字符串。

案例

全部替换字符串

使用 strings.ReplaceAll() 函数,替换全部字符串

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 strings.ReplaceAll() 函数,替换全部字符串 strHaiCoder := "HaiCoder嗨客网HaiCoder" strReplaceAll := strings.ReplaceAll(strHaiCoder, "HaiCoder", "haicoder") fmt.Println("StrReplaceAll =", strReplaceAll) }

程序运行后,控制台输出如下:

87 golang字符串替换replaceAll.png

首先,我们定义了一个字符串类型的 变量 strHaiCoder,接着我们使用字符串的 strings.ReplaceAll() 函数将变量 strHaiCoder 中的字符串 “HaiCoder” 全部替换成了 “haicoder”,结果返回替换后的字符串。

Go语言字符串全部替换总结

在 Go 语言中,将某个字符串全部替换成新的字符串的需求,我们可以通过 strings.ReplaceAll() 函数来实现。Go 语言 strings.ReplaceAll() 函数语法:

func ReplaceAll(s, old, new string) string