Go文字列内で置換を行う方法
Go言語では、文字列の置換はstrings.Replace関数で行うことができます。この関数の定義は以下の通りです。
func Replace(s, old, new string, n int) string
パラメータsは元の文字列、パラメータoldは置き換えられる文字列、パラメータnewは置き換え後の文字列、パラメータnは最大置き換え回数です(nが0以下の場合はすべての一致した文字列が置き換えられます)。
以下のサンプルコードは、strings.Replace関数を用いて文字列置換を行う方法を示します。
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello world"
newStr := strings.Replace(str, "world", "go", -1)
fmt.Println(newStr) // 输出: hello go
}
上のコードでは、元の文字列の “world” を “go” に置き換え、置き換えた結果を出力します。出力結果は “hello go” です。