How to repeat a string for a specified number of times in Golang?


strings.Repeat() is a built-in function in Golang that is used to repeat a string for a specified number of times. It returns a new string which consists of a new count of copies of the given string.

Syntax

Its syntax is as follows −

func Repeat(s string, count int) string

Where s is the given string and count represents how many times you want to repeat the string. It returns a new string.

Example 1

The following example demonstrates how you can use the Repeat() function −

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   x := "Object"
   y := "Web"
   z := "Libraries"
   w := "123"

   // Display the Strings
   fmt.Println("String 1:", x)
   fmt.Println("String 2:", y)
   fmt.Println("String 3:", z)
   fmt.Println("String 4:", w)
   
   // Using the Repeat Function
   result1 := strings.Repeat(x, 2)
   result2 := strings.Repeat(y, 1)
   result3 := strings.Repeat(z, 3)
   result4 := w + strings.Repeat("45", 2)

   // Display the Repeat Output
   fmt.Println("Repeat String 1 Twice:", result1)
   fmt.Println("Repeat String 2 Once:", result2)
   fmt.Println("Repeat String 3 Thrice:", result3)
   fmt.Println("String 4 + Repeat '45' Twice:", result4)
}

Output

It will generate the following output −

String 1: Object
String 2: Web
String 3: Libraries
String 4: 123
Repeat String 1 Twice: ObjectObject
Repeat String 2 Once: Web
Repeat String 3 Thrice: LibrariesLibrariesLibraries
String 4 + Repeat '45' Twice: 1234545

Example 2

The Repeat() function will panic if the value of the count is negative or the result of (len(slice_1) * count) overflows. Consider the following example −

package main
import (
   "fmt"
   "strings"
)
func main() {
   var p string
   var q string
   
   // Intializing the Strings
   p = "Programming"
   q = "Web"

   // Display the Strings
   fmt.Println("String 1:", p)
   fmt.Println("String 2:", q)
   
   // Using the Repeat Function
   output1 := strings.Repeat(p, 2)
   output2 := q + strings.Repeat(" Development", -1)

   // Display the Repeat Output
   fmt.Println("Repeat String 1 Twice:", output1)
   fmt.Println("String 2 + Repeat 'Development':", output2)
}

Output

It will generate the following output −

String 1: Programming
String 2: Web
panic: strings: negative Repeat count

goroutine 1 [running]:
strings.Repeat(0x4b0445, 0xc, 0xffffffffffffffff, 0xc42000a260, 0x16)
/usr/lib/golang/src/strings/strings.go:432 +0x258
main.main()
/home/cg/root/9328426/main.go:17 +0x272
exit status 2

Updated on: 10-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements