go言語 文字列を置換する

  • 作成日 2021.04.09
  • 更新日 2022.11.03
  • go
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

}