To repeat a given string in Go, you should use the strings.Repeat()
perform from the strings
package deal.
It takes a string and the variety of instances it must be repeated as arguments and returns the multiplied string as output. The perform panics if depend
is detrimental or if len(s) * depend
overflows.
Take a look at the next instance:
|
|
Output:
gosamples.dev gosamples.dev gosamples.dev
------------------------------------------
In line 11
, we create a brand new multiplied string which is the string "gosamples.dev "
repeated 3 times. Then, in line 12
, we wish to make a line separator consisting of a repeated -
character. Its size must be equal to the variety of characters of the earlier string.
Notice that we use the utf8.RuneCountInString()
perform to depend the variety of characters as an alternative of len()
. The previous counts the runes (Unicode code factors) within the string, whereas the latter counts the variety of bytes. When counting characters in a string "gosamples.dev gosamples.dev gosamples.dev "
, each features will return the identical quantity; nevertheless it’s good to make a behavior of utilizing utf8.RuneCountInString()
while you wish to depend the variety of characters. It should forestall incorrect outcomes while you change the enter string:
s := "€€€"
fmt.Println(len(s))
fmt.Println(utf8.RuneCountInString(s))
The € (euro) image is a three-byte character, encoded in UTF-8 with bytes 0xE2, 0x82, 0xAC.