要在Go中重复一个给定的字符串,你可以使用 strings.Repeat()函数,该函数来自 strings包中的函数。
func Repeat(s string, count int) string
它以一个字符串和它应该被重复的次数为参数,并将被乘的字符串作为输出返回。如果count 是负数,或者len(s) * count 溢出,该函数就会发生恐慌。
请看下面的例子。
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
s := "gosamples.dev "
repeated := strings.Repeat(s, 3)
lineSeparator := strings.Repeat("-", utf8.RuneCountInString(repeated))
fmt.Println(repeated)
fmt.Println(lineSeparator)
}
输出:
gosamples.dev gosamples.dev gosamples.dev
------------------------------------------
在11 行,我们创建了一个新的乘法字符串,即重复三次的字符串"gosamples.dev " 。然后,在第12 行,我们要制作一个由重复的- 字符组成的行分隔符。其长度应等于前一个字符串的字符数。
请注意,我们使用 utf8.RuneCountInString()函数来计算字符的数量,而不是 len().前者是计算字符串中的符点(Unicode代码点),而后者是计算字节数。当计算字符串中的字符数时,"gosamples.dev gosamples.dev gosamples.dev " ,这两个函数将返回相同的数字;然而,最好是养成习惯,当你想计算字符数时,使用 utf8.RuneCountInString()当你想计算字符数的时候,最好养成使用这将防止在你改变输入字符串时出现不正确的结果。
s := "€€€"
fmt.Println(len(s))
fmt.Println(utf8.RuneCountInString(s))
9
3
€(欧元)符号是一个三字节的字符,在UTF-8中被编码为0xE2, 0x82, 0xAC字节。