生成一个包含N个空格的字符串的规范方法是什么?

huangapple go评论88阅读模式
英文:

Canonical method to generate a string of N spaces?

问题

在Go语言中,生成一个由N个空格组成的字符串的规范方法类似于Python中的' ' * n。你目前正在自己构建这个方法,代码如下:

func spaces(n int) string {
    var sb strings.Builder
    for i := 0; i < n; i++ {
        sb.WriteString(" ")
    }
    return sb.String()
}

这段代码使用了strings.Builder类型来构建字符串,并通过循环向其中添加空格。最后,使用sb.String()方法将strings.Builder对象转换为字符串并返回。

英文:

What is the canonical method of generating a string of N spaces in Go, similar to &#39; &#39; * n in Python?

I am currently building it myself as follows.

func spaces(n int) string {
    var sb strings.Builder
    for i := 0; i &lt; n; i++ {
        sb.WriteString(&quot; &quot;)
    }
    return sb.String()
}

答案1

得分: 6

标准库中有一个 strings.Repeat 函数,所以 strings.Repeat(" ", n) 可以实现相同的功能。这个函数的实现方式与你的代码类似,但有以下区别:

  1. 它在使用 strings.Builder 之前提前调用了 Grow 方法,以保证只有一次内存分配,而不是可能在中间多次重新分配。

  2. 它逐步将构建器的内容倍增,而不是调用 WriteString 方法 n 次。这样做可能更高效。

对于合理数量的空格,这些区别可能并不重要...但无论如何,标准库中有一个函数可以表达你的意思(实际上它是 Python 中 str * int 的直接等价),所以你可以直接使用它。

英文:

There's a strings.Repeat function in the standard library, so strings.Repeat(&quot; &quot;, n) would do. The implementation uses a strings.Builder like yours, except:

  1. It calls Grow on the builder ahead of time to guarantee only one allocation, instead of possibly reallocating several times in the middle.

  2. It progressively doubles the content of the builder instead of calling WriteString n times. Presumably they do that because it's more efficient.

For reasonable numbers of spaces, none of that probably makes any difference... but anyway, there's a stdlib function that expresses what you mean (really it's the direct equivalent of Python's str * int), so you might as well use it.

huangapple
  • 本文由 发表于 2022年12月20日 10:34:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/74857990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定