Fastest way to create string of the same character in Go

huangapple go评论87阅读模式
英文:

Fastest way to create string of the same character in Go

问题

我想知道创建一个由相同字符的n个实例组成的字符串的最快方法是什么。我可以想象几种方法,有些天真,有些不太天真:

字符串拼接(非常天真)

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

字节切片

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

I'm wondering what the fastest way would be to create a string of n instances of the same character. I could imagine a few approaches, some naive and some less so:

String concatenation (very naive)

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

Byte slice

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

答案1

得分: 8

字节切片的方法至少在strings.Repeat中被选择:请参考它的源代码

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

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

英文:

The byte slice approach is at least the one chosen in strings.Repeat: see its source:

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

So I would go with your second choice.

答案2

得分: 4

res1 := strings.Repeat(str1, 4) 的中文翻译是:res1 := strings.Repeat(str1, 4)。

英文:
res1 := strings.Repeat(str1, 4)

huangapple
  • 本文由 发表于 2014年8月21日 18:37:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/25424184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定