Golang 重复一个字符串的特定次数

Golang 重复一个字符串的特定次数

在Go语言中,字符串与其他语言如Java、C++、Python等不同。它是一个宽度可变的字符序列,每一个字符都由一个或多个使用UTF-8编码的字节表示。

Repeat() 函数的帮助下,你可以重复一个字符串的特定次数。该方法返回一个包含重复字符串的新字符串,它被定义在strings包中。因此,你必须在你的程序中导入strings包以访问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..

注意: 如果count的值为负数或者(len(str)*count)的结果溢出,这个方法就会发生恐慌。

例子2 :

// 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

例3:使用for循环

// Go program to illustrate how to repeat
// a string to a specific number of times
package main
 
import (
    "fmt"
)
 
// Main method
func main() {
 
    // Creating and initializing a string
    // Using shorthand declaration
    str1 := "Welcome to GeeksforGeeks !.."
 
    // Repeating the given strings
    i := 0
    res1 := " "
    for i < 3 {
        res1 += str1
        i += 1
    }
 
    // Display the results
    fmt.Println("Result 1: ", res1)
 
}

输出

Result 1:   Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..Welcome to GeeksforGeeks !..

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程