go语言怎么替换字符串

青灯夜游
青灯夜游 原创
2023-01-10 17:17:15 2542浏览

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

本教程操作环境: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))
}

1.png

替换字符串多次

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

2.png

替换所有字符串

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

3.png

【相关推荐:Go视频教程编程教学

以上就是go语言怎么替换字符串的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。