如何在Go语言中重复字符串指定次数?
**strings.Repeat()** 是Go语言中的一个内置函数,用于将字符串重复指定次数。它返回一个由给定字符串的多个副本组成的新字符串。
语法
其语法如下:
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()**函数将引发panic。考虑以下示例:
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
广告
数据结构
网络
关系型数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP