• 技术文章 >后端开发 >Golang

    go语言怎么替换字符串

    青灯夜游青灯夜游2023-01-10 17:17:15原创70

    在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。

    返回值

    说明

    使用示例:

    替换一次字符串

    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核实处理。
    专题推荐:go语言 Golang
    上一篇:Go语言变量的生命周期是啥 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • Go语言中匿名变量是什么• Go中数值类型有几种• Go语言切片可以多维吗• go语言中make和new的区别是什么• Go语言的变量有几种类型• Go语言中copy()怎么用
    1/1

    PHP中文网