在go語(yǔ)言中,可以利用strings包的Replace()函數(shù)來替換字符串,語(yǔ)法“strings.Replace(原字符串,要搜索的值,替換值,替換次數(shù))”;如果替換次數(shù)為負(fù)數(shù),那么表明將字符串中所有的指定子串全部替換成新值。
本教程操作環(huán)境:windows7系統(tǒng)、GO 1.18版本、Dell G3電腦。
在開發(fā)過程中,有時(shí)候我們需要將一個(gè) 字符串 中特定的字符串替換成新的字符串的需求,在 Go 語(yǔ)言 中,將某個(gè)字符串替換成新的字符串的需求,我們可以通過 strings.Replace() 函數(shù) 來實(shí)現(xiàn)。
strings.Replace()函數(shù)
語(yǔ)法
func Replace(s, old, new string, n int) string
登錄后復(fù)制
參數(shù) | 描述 |
---|---|
s | 要替換的整個(gè)字符串。 |
old | 要替換的字符串。 |
new | 替換成什么字符串。 |
n | 要替換的次數(shù),-1,那么就會(huì)將字符串 s 中的所有的 old 替換成 new。 |
返回值
-
返回替換后的字符串。
說明
-
將字符串 s 中的 old 字符串替換成 new 字符串,替換 n 次,返回替換后的字符串。如果 n 是 -1,那么就會(huì)將字符串 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)) }
登錄后復(fù)制
替換字符串多次
package main import ( "fmt" "strings" ) func main() { //使用 strings.Replace() 函數(shù),替換字符串 strHaiCoder := "hello你好hello" fmt.Println("StrReplace =", strings.Replace(strHaiCoder, "hello", "hi", 2)) }
登錄后復(fù)制
替換所有字符串
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)) }
登錄后復(fù)制
【