• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

go语言怎么替换字符串

武飞扬头像
PHP中文网
帮助207

在开发过程中,有时候我们需要将一个 字符串 中特定的字符串替换成新的字符串的需求,在 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))
}

学新通技术网

替换字符串多次

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

学新通技术网

替换所有字符串

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

学新通技术网

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanfffgf
系列文章
更多 icon
同类精品
更多 icon
继续加载