go言語 文字列を置換する

go言語で、stringsパッケージのReplaceを使用して、文字列を置換するサンプルコードを記述してます。go言語のバージョンは1.15.4を使用してます。
環境
- OS windows10 pro 64bit
- go言語 1.15.4
Replace使い方
Replaceを使用すると、文字列を置換することが可能です。
strings.Replace(文字列, 判定したい文字列)
strings.HasSuffix(文字列, 置換したい文字列, 置換後の文字列, 回数)
// 回数は-1を指定すると全てになります。
以下は、Replaceを使って、文字列「hello world hello world hello world」を置換するサンプルコードとなります。
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello world hello world hello world"
fmt.Println(strings.Replace(str, "hello", "world", 1))
// world world hello world hello world
fmt.Println(strings.Replace(str, "hello", "world", 2))
// world world world world hello world
fmt.Println(strings.Replace(str, "hello", "world", -1))
// world world world world world world
fmt.Println(strings.Replace(str, " ", "", -1))
// helloworldhelloworldhelloworld
}
-
前の記事
javascript onkeydownでキーが押されたイベントを取得する 2021.04.09
-
次の記事
mountしたディレクトリが「 Permission denied」が発生して操作できない場合 2021.04.09
コメントを書く