strings.Replace() Golang中的函數用於返回給定字符串的副本,其中前n個不重疊的舊實例被新實例替換。
用法:
func Replace(s, old, new string, n int) string
在這裏,s是原始或給定的字符串,old是您要替換的字符串。 new是替換舊版本的,n是舊替換的次數。
注意:如果old為空,則它在字符串的開頭和每個UTF-8序列之後匹配,最多可對k-rune字符串進行k + 1個替換。如果n <0,則替換次數沒有限製。
範例1:
// Golang program to illustrate the usage of
// strings.Replace() function
package main
import (
"fmt"
"strings"
)
func main() {
// using the function
fmt.Println(strings.Replace("gfg gfg gfg", "g", "G", 3))
fmt.Println(strings.Replace("gfg gfg gfg", "fg", "FG", -1))
}
輸出:
GfG Gfg gfg gFG gFG gFG
在第一種情況下,“gfg gfg gfg”中“g”的前3個匹配子字符串被“G”替換。在第二種情況下,每個匹配的“fg”情況都被“FG”取代。
範例2:讓我們考慮一個示例,其中我們不傳遞任何舊值。
// Golang program to illustrate the usage of
// strings.Replace() function
package main
import (
"fmt"
"strings"
)
func main() {
// using the function
fmt.Println(strings.Replace("i am geeks", "", "G", 5))
fmt.Println(strings.Replace("i love the geekiness", "", "F", -1))
}
輸出:
GiG GaGmG geeks FiF FlFoFvFeF FtFhFeF FgFeFeFkFiFnFeFsFsF
可以看出,每個替代位置都被n次替換。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自supergops大神的英文原創作品 strings.Replace() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。