gpt4 book ai didi

string - 在 Go 中创建相同字符的字符串的最快方法

转载 作者:IT王子 更新时间:2023-10-29 01:22:24 30 4
gpt4 key购买 nike

我想知道创建具有相同字符的 n 个实例的最快方法是什么。我可以想象一些方法,有些比较幼稚,有些则不那么幼稚:

字符串连接(非常幼稚)

func nchars(b byte, n int) string {
s := ""
c := string([]byte{b})
for i := 0; i < n; i++ {
s += c
}
return s
}

字节 slice

func nchars(b byte, n int) string {
s := make([]byte, n)
for i := 0; i < n; i++ {
s[i] = b
}
return string(s)
}

最佳答案

字节 slice 方法至少是 strings.Repeat 中选择的一种方法:见its source :

b := make([]byte, len(s)*count)
bp := 0
for i := 0; i < count; i++ {
bp += copy(b[bp:], s)
}
return string(b)

所以我会选择你的第二个选择。

关于string - 在 Go 中创建相同字符的字符串的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25424184/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com