Golang 如何重复一个字符串的指定次数
strings.Repeat() 是Golang中的一个内置函数,用于重复一个字符串的指定次数。它返回一个新的字符串,该字符串由给定字符串的新副本数组成。
语法
它的语法如下
func Repeat(s string, count int) string
其中 s 是给定的字符串,count代表你想重复多少次的字符串。它返回一个新的字符串。
例子1
下面的例子演示了如何使用 Repeat() 函数。
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)
}
输出
它将产生以下输出 –
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
例2
如果 count 的值是负的,或者 (len(slice_1) * count)
的结果溢出, Repeat( )函数会恐慌。考虑下面的例子 –
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)
}
输出
它将产生以下输出 –
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