零零乙 2009-11-19 03:44 采纳率: 33.3%
浏览 438
已采纳

如何有效地连接 Go 中的字符串?

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?

The naive way would be:

s := ""
for i := 0; i < 1000; i++ {
    s += getShortStringFromSomewhere()
}
return s

but that does not seem very efficient.

转载于:https://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go

  • 写回答

20条回答 默认 最新

  • 零零乙 2009-11-19 20:31
    关注

    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.

    Note added in 2018

    From Go 1.10 there is the strings.Builder type, which achieves this even more efficiently (for strings). The example given there is succinct and easy to copy/adapt.

    This is analogous to the StringBuilder class in Java.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(19条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况