站长资讯网
最全最丰富的资讯网站

go语言怎么替换字符串

在go语言中,可以利用strings包的Replace()函数来替换字符串,语法“strings.Replace(原字符串,要搜索的值,替换值,替换次数)”;如果替换次数为负数,那么表明将字符串中所有的指定子串全部替换成新值。

go语言怎么替换字符串

本教程操作环境:windows7系统、GO 1.18版本、Dell G3电脑。

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

strings.Replace()函数

语法

func Replace(s, old, new string, n int) string
登录后复制

参数 描述
s 要替换的整个字符串。
old 要替换的字符串。
new 替换成什么字符串。
n 要替换的次数,-1,那么就会将字符串 s 中的所有的 old 替换成 new。

返回值

  • 返回替换后的字符串。

说明

  • 将字符串 s 中的 old 字符串替换成 new 字符串,替换 n 次,返回替换后的字符串。如果 n 是 -1,那么就会将字符串 s 中的所有的 old 替换成 new。

使用示例:

替换一次字符串

package main import ( 	"fmt" 	"strings" ) func main() { 	//使用 strings.Replace() 函数,替换字符串 	strHaiCoder := "hello你好hello" 	fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 1)) }
登录后复制

go语言怎么替换字符串

替换字符串多次

package main import ( 	"fmt" 	"strings" ) func main() { 	//使用 strings.Replace() 函数,替换字符串 	strHaiCoder := "hello你好hello" 	fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 2)) }
登录后复制

go语言怎么替换字符串

替换所有字符串

package main import ( 	"fmt" 	"strings" ) func main() { 	//使用 strings.Replace() 函数,替换字符串 	strHaiCoder := "hello你好hello你好hello你好hello你好hello" 	fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", -1)) }
登录后复制

go语言怎么替换字符串

赞(0)
分享到: 更多 (0)