必承其重 | 欲带皇冠 2009-11-19 03:44 采纳率: 0%
浏览 457
已采纳

如何有效地连接 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条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题