新聞中心
這篇文章主要介紹“go語言如何替換字符串”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“go語言如何替換字符串”文章能幫助大家解決問題。
創(chuàng)新互聯(lián)建站主營浦江網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,APP應(yīng)用開發(fā),浦江h(huán)5重慶小程序開發(fā)公司搭建,浦江網(wǎng)站營銷推廣歡迎浦江等地區(qū)企業(yè)咨詢
在go語言中,可以利用strings包的Replace()函數(shù)來替換字符串,語法“strings.Replace(原字符串,要搜索的值,替換值,替換次數(shù))”;如果替換次數(shù)為負數(shù),那么表明將字符串中所有的指定子串全部替換成新值。
在開發(fā)過程中,有時候我們需要將一個 字符串 中特定的字符串替換成新的字符串的需求,在 Go 語言 中,將某個字符串替換成新的字符串的需求,我們可以通過 strings.Replace() 函數(shù) 來實現(xiàn)。
strings.Replace()函數(shù)
語法
func Replace(s, old, new string, n int) string
參數(shù) | 描述 |
---|---|
s | 要替換的整個字符串。 |
old | 要替換的字符串。 |
new | 替換成什么字符串。 |
n | 要替換的次數(shù),-1,那么就會將字符串 s 中的所有的 old 替換成 new。 |
返回值
返回替換后的字符串。
說明
將字符串 s 中的 old 字符串替換成 new 字符串,替換 n 次,返回替換后的字符串。如果 n 是 -1,那么就會將字符串 s 中的所有的 old 替換成 new。
使用示例:
替換一次字符串
package main
import (
"fmt"
"strings"
)
func main() {
//使用 strings.Replace() 函數(shù),替換字符串
strHaiCoder := "hello你好hello"
fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 1))
}
替換字符串多次
package main
import (
"fmt"
"strings"
)
func main() {
//使用 strings.Replace() 函數(shù),替換字符串
strHaiCoder := "hello你好hello"
fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 2))
}
替換所有字符串
package main
import (
"fmt"
"strings"
)
func main() {
//使用 strings.Replace() 函數(shù),替換字符串
strHaiCoder := "hello你好hello你好hello你好hello你好hello"
fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", -1))
}
關(guān)于“go語言如何替換字符串”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。
當前名稱:go語言如何替換字符串
標題鏈接:http://www.dlmjj.cn/article/ggchji.html