用户登录
用户注册

分享至

go语言怎么替换字符串

  • 作者: 神器一百九十毫米
  • 来源: 51数据库
  • 2023-01-12

在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语言怎么替换字符串的详细内容,更多请关注其它相关文章!

软件
前端设计
程序设计
Java相关