必承其重 | 欲带皇冠 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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路