Cookies management by TermsFeed Cookie Consent

🔁 Repeat a string in Go

shorts strings

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    s := "gosamples.dev "
    repeated := strings.Repeat(s, 3)
    lineSeparator := strings.Repeat("-", utf8.RuneCountInString(repeated))

    fmt.Println(repeated)
    fmt.Println(lineSeparator)
}

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.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🐾 How to compare strings in Go

shorts introduction strings

🥇 How to uppercase the first letter of each word in Go

shorts strings

🔠 String to uppercase in Go

shorts strings