如何在Go中有效地串联字符串 [英] How to efficiently concatenate strings in go
本文介绍了如何在Go中有效地串联字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Go中,string
是原始类型,这意味着它是只读的,对其的每次操作都会创建一个新的字符串.
In Go, a string
is a primitive type, which means it is read-only, and every manipulation of it will create a new string.
因此,如果我想多次连接字符串而又不知道结果字符串的长度,那么最好的方法是什么?
So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?
天真的方法是:
var s string
for i := 0; i < 1000; i++ {
s += getShortStringFromSomewhere()
}
return s
但这似乎不是很有效.
推荐答案
新方法:
从Go 1.10开始,有一个strings.Builder
类型,请查看此答案以获取更多详细信息.
使用 bytes
包.它具有 Buffer
类型,该类型实现了
Use the bytes
package. It has a Buffer
type which implements io.Writer
.
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
fmt.Println(buffer.String())
}
这是在O(n)时间完成的.
This does it in O(n) time.
这篇关于如何在Go中有效地串联字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文