如何在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