Home »
Golang »
Golang Reference
Golang strings.Repeat() Function with Examples
Golang | strings.Repeat() Function: Here, we are going to learn about the Repeat() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 19, 2021
strings.Repeat()
The Repeat() function is an inbuilt function of strings package which is used to create a string consisting of count copies of the given string. It accepts two parameters – string and count, and returns a new string consisting of count copies of the string.
Note: The function may return an error if the value of count is -1 or len(string)*count overflows.
Syntax
func Repeat(str string, count int) string
Parameters
- str : The main string to be used to create a new string.
- count : Count of copies of the string (str).
Return Value
The return type of Repeat() function is a string, it returns a new string consisting of count copies of the string.
Example 1
// Golang program to demonstrate the
// example of strings.Repeat() Function
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Repeat("Hello, world! ", 2))
fmt.Println(strings.Repeat("Hello, world! ", 4))
fmt.Println(strings.Repeat("Hi, ", 2))
fmt.Println("Hey world! " + strings.Repeat("Hi! ", 5))
}
Output:
Hello, world! Hello, world!
Hello, world! Hello, world! Hello, world! Hello, world!
Hi, Hi,
Hey world! Hi! Hi! Hi! Hi! Hi!
Example 2
// Golang program to demonstrate the
// example of strings.Repeat() Function
package main
import (
"fmt"
"strings"
)
func main() {
var str string
var count int
var new_string string
str = "Hello, world! "
count = 5
new_string = strings.Repeat(str, count)
fmt.Printf("str: %q, count: %d\n", str, count)
fmt.Printf("new_string: %q\n", new_string)
str = "This is a program."
count = 2
new_string = strings.Repeat(str, count)
fmt.Printf("str: %q, count: %d\n", str, count)
fmt.Printf("new_string: %q\n", new_string)
str = "Hibiscus Iced Tea at Starbuck. "
count = 2
new_string = strings.Repeat(str, count)
fmt.Printf("str: %q, count: %d\n", str, count)
fmt.Printf("new_string: %q\n", new_string)
}
Output:
str: "Hello, world! ", count: 5
new_string: "Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! "
str: "This is a program.", count: 2
new_string: "This is a program.This is a program."
str: "Hibiscus Iced Tea at Starbuck. ", count: 2
new_string: "Hibiscus Iced Tea at Starbuck. Hibiscus Iced Tea at Starbuck. "
Golang strings Package Functions »