Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
repeat
strings
communitycreator

How to create repetition of a string in Go

Siddharth Singh

The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.

strings provides the Repeat() method, which can be used to create repetition of a string by a specified number of times.

Syntax


func Repeat(s string, count int) string

Parameters

  • The Repeat() method takes a string s and an integer count as input.

  • Repeat() returns a new string that consists of count copies of the input string s.

  • A panic is fired if the count is negative.

  • This method also panics if the result of the length of the input string multiplied by count overflows.

Return type

The Repeat() method returns a new string that consists of copies of the passed input string. The number of repetitions is also passed as input to this method.

Code

In the code below, we first import the fmt and strings packages to our program.

package main

import (
	"fmt"
	"strings"
)

func main() {
  str1 := "abc"
  fmt.Println("Calling Repeat('abc',4)")
	fmt.Println(strings.Repeat(str1, 4))

  fmt.Println("\nCalling Repeat('ca',5)")
  str3 := strings.Repeat("ca",5)
  fmt.Println(str3)

}

Explanation

We call the Repeat() method, with abc as the input string and 4 as the count. This returns abcabcabcabc, which is abc repeated four times.

We call the Repeat() method again, with ca as the input string and 5 as the count. This returns cacacacaca, which is ca repeated five times.

We display the output of all these operations with the Println() method of the fmt package.

The program prints the output below and exits.


Calling Repeat('abc',4)
abcabcabcabc

Calling Repeat('ca',5)
cacacacaca

RELATED TAGS

go
golang
repeat
strings
communitycreator
RELATED COURSES

View all Courses

Keep Exploring