LoginSignup
0
0

More than 1 year has passed since last update.

Golang同じ文字列を繰り返して連結する方法

Posted at

Golang での同じ文字列を繰り返して連結する方法

  • 環境
$ go version
go version go1.17.2 darwin/amd64
  • 方法
package main

import (
	"bytes"
	"strings"
)

func main() {
	// repeat byte
	bufBytes := []byte("😺")
	println("repeat byte:" + string(bytes.Repeat(bufBytes, 3))) //😺😺😺

	// repeat strings
	str := "😺"
	println("repeat strings:" + strings.Repeat(str, 3)) //😺😺😺

	// repeat rune
	// rune 型のスライスにはrepeat関数が用意されていないため、for 文を使う必要がある。
	bufRunes := []rune("😺")
	for i := 0; i < 3; i++ {
		bufRunes = append(bufRunes, []rune("😺")...)
	}
	println("repeat runes:" + string(bufRunes)) //😺😺😺

}
repeat byte:😺😺😺
repeat strings:😺😺😺
repeat runes:😺😺😺😺

Program exited.

Golang Playground Demo

注意:ちなみに、stringsの場合は、+ による連結もできますが、Repeat()の方がパフォーマンス的に良いです。

おまけ

ご参考まで、他の言語の書き方もまとめますと、

言語 方法
Go 言語 strings.Repeat(str, 3)
Scala str * 3
Groovy str * 3
PHP str_repeat($str, 3)
Python str * 3
Ruby str * 3
Perl $str x 3

参考記事

同じ文字列を繰り返して連結するには(文字列の乗算みたいな)

元記事

Golang:同じ文字列を繰り返して連結する方法

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0