To repeat a given string in Go, you can use the strings.Repeat()
function from the strings
package.
It takes a string and the number of times it should be repeated as arguments and returns the multiplied string as output. The function panics if count
is negative or if len(s) * count
overflows.
Look at the following example:
|
|
Output:
gosamples.dev gosamples.dev gosamples.dev
------------------------------------------
In line 11
, we create a new multiplied string which is the string "gosamples.dev "
repeated three times. Then, in line 12
, we want to make a line separator consisting of a repeated -
character. Its length should be equal to the number of characters of the previous string.
Note that we use the utf8.RuneCountInString()
function to count the number of characters instead of len()
. The former counts the runes (Unicode code points) in the string, while the latter counts the number of bytes. When counting characters in a string "gosamples.dev gosamples.dev gosamples.dev "
, both functions will return the same number; however it is good to make a habit of using utf8.RuneCountInString()
when you want to count the number of characters. It will prevent incorrect results when you change the input string:
s := "€€€"
fmt.Println(len(s))
fmt.Println(utf8.RuneCountInString(s))
9
3
The € (euro) symbol is a three-byte character, encoded in UTF-8 with bytes 0xE2, 0x82, 0xAC.