在 Go 语言中,字符串不同于Java、C++、 Python等其他语言。它是一系列可变宽度字符,其中每个字符都由一个或多个使用 UTF-8 编码的字节表示。
您可以在Repeat()函数的帮助下将字符串重复特定次数。此方法返回一个包含重复字符串的新字符串,它在字符串包下定义。因此,您必须在程序中导入字符串包才能访问重复函数。
句法:
func Repeat(str string, count int) string
这里, str表示您要重复的字符串,而 count 值表示您要重复 str 字符串。
示例 1:
// Go program to illustrate how to repeat
// a string to a specific number of times
package main
import (
"fmt"
"strings"
)
// Main method
func main() {
// Creating and initializing a string
// Using shorthand declaration
str1 := "Welcome to GeeksforGeeks !.."
str2 := "This is the tutorial of Go"
// Repeating the given strings
// Using Repeat function
res1 := strings.Repeat(str1, 4)
res2 := str2 + strings.Repeat("Language..", 2)
// Display the results
fmt.Println("Result 1: ", res1)
fmt.Println("Result 2:", res2)
}
输出:
Result 1: Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..
Result 2: This is the tutorial of GoLanguage..Language..
注意:如果计数的值为负或 (len(str) * count) 的结果溢出,则此方法将发生恐慌。
例子:
// Go program to illustrate how to repeat
// a string to a specific number of times
package main
import (
"fmt"
"strings"
)
// Main method
func main() {
// Creating and initializing a string
// Using shorthand declaration
str1 := "Welcome to GeeksforGeeks !.."
str2 := "This is the tutorial of Go"
// Repeating the given strings
// Using Repeat function
res1 := strings.Repeat(str1, 4)
// If we use a negative value in the count
// then this method will panic because negative
// values are not allowed to count
res2 := str2 + strings.Repeat("Language..", -2)
// Display the results
fmt.Println("Result 1: ", res1)
fmt.Println("Result 2:", res2)
}
输出:
panic: strings: negative Repeat count
goroutine 1 [running]:
strings.Repeat(0x104b22, 0xa, 0xfffffffe, 0x0, 0x450000, 0x70)
/usr/local/go/src/strings/strings.go:533 +0x540
main.main()
/tmp/sandbox829702598/prog.go:25 +0x80