![does does](https://c1.lmlphp.com/image/static/default_avatar.gif)
本文介绍了如何在Go中高效地连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Go中,string是一个原始类型,它是只读的,对它的每个操作都会创建一个新的字符串。
因此,如果我想多次连接字符串而不知道结果字符串的长度,那么最好的方法是什么?
天真的方式是:
s:=
for i:= 0;我< 1000; i ++ {
s + = getShortStringFromSomewhere()
}
返回s
但看起来效率并不高。 解决方案
最好的方法是使用包。它有一个类型,它实现。
package main
import(
bytes
fmt
)
func main(){
var buffer bytes.Buffer
for i:= 0;我< 1000; i ++ {
buffer.WriteString(a)
}
fmt.Println(buffer.String())
}
这是在O(n)时间内完成的。
In Go, string is a primitive type, it's readonly, every manipulation to 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?
The naive way would be:
s := ""
for i := 0; i < 1000; i++ {
s += getShortStringFromSomewhere()
}
return s
but that does not seem very efficient.
解决方案
The best way is to 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())
}
This does it in O(n) time.
这篇关于如何在Go中高效地连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!