Home >Backend Development >Golang >How to repeat a string in go language
In the Go language, you can use the Repeat() function in the Strings package to repeat a string; this function can repeat a string a specified number of times
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
In the go language, you can use the Repeat() function in the Strings package to repeat a string.
Strings.Repeat() function can repeat a string a specified number of times.
func Repeat(s string, count int) string
Parameters | Description |
---|---|
s | Original string. |
count | The number of times to repeat. |
Return value
The new string returned after repeating count times.
Example 1: Repeat string 4 times
In this program, we will use strings.Repeat() function by specified number of times Repeats the specified string and prints the results on the console screen.
// Golang program to demonstrate the // strings.Repeat() function package main import "fmt" import "strings" func main() { var str string = "India " var result string result = strings.Repeat(str, 4) fmt.Println("String After repetition:", result) }
Explanation:
In the above program, we declared the package main. The main package is used to tell the Go language compiler that this package must be compiled and generate an executable file. Here we have imported the fmt package which contains the fmt package files and then we can use the functions related to the fmt package.
In the main() function, we created two variables str and result. Then we use the strings.Repeat() function to repeat the specified string 4 times and assign it to the result variable. After that, we print the results on the console screen.
Example 2: Repeat the string 0 times
// Golang program to demonstrate the // strings.Repeat() function package main import "fmt" import "strings" func main() { var str string = "India " var result string result = strings.Repeat(str, 0) fmt.Println("String After repetition:", result) }
It can be seen that using the string The strings.Repeat() function repeats the variable str 0 times and returns an empty string.
【Related recommendations: Go video tutorial, Programming teaching】
The above is the detailed content of How to repeat a string in go language. For more information, please follow other related articles on the PHP Chinese website!