Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 我可以用make或new在golang中制作预填充字符串吗?_String_Go_Buffer_Slice - Fatal编程技术网

String 我可以用make或new在golang中制作预填充字符串吗?

String 我可以用make或new在golang中制作预填充字符串吗?,string,go,buffer,slice,String,Go,Buffer,Slice,我正在尝试在Go中优化我的stringpad库。到目前为止,我发现用已知字符值(例如0或“”)填充字符串(实际上是bytes.Buffer)的唯一方法是使用for循环 代码片段是: // PadLeft pads string on left side with p, c times func PadLeft(s string, p string, c int) string { var t bytes.Buffer if c <= 0 { return s

我正在尝试在Go中优化我的stringpad库。到目前为止,我发现用已知字符值(例如0或“”)填充字符串(实际上是bytes.Buffer)的唯一方法是使用for循环

代码片段是:

// PadLeft pads string on left side with p, c times
func PadLeft(s string, p string, c int) string {
    var t bytes.Buffer
    if c <= 0 {
        return s
    }
    if len(p) < 1 {
        return s
    }
    for i := 0; i < c; i++ {
        t.WriteString(p)
    }
    t.WriteString(s)
    return t.String()
}
//PadLeft在左侧用p,c次填充字符串
func PadLeft(s字符串、p字符串、c int)字符串{
var t字节。缓冲区
如果c,则只能使用和来分配归零的缓冲区(字节片或数组)。可以使用来获取最初包含非零值的片或数组,但不能动态描述初始值(索引必须是常量)

从类似但非常有效的函数中汲取灵感。它以给定的计数重复给定的字符串:

func Repeat(s string, count int) string {
    // Since we cannot return an error on overflow,
    // we should panic if the repeat will generate
    // an overflow.
    // See Issue golang.org/issue/16237
    if count < 0 {
        panic("strings: negative Repeat count")
    } else if count > 0 && len(s)*count/count != len(s) {
        panic("strings: Repeat count causes overflow")
    }

    b := make([]byte, len(s)*count)
    bp := copy(b, s)
    for bp < len(b) {
        copy(b[bp:], b[:bp])
        bp *= 2
    }
    return string(b)
}
测试它:

fmt.Println(PadLeft("aa", "x", 1))
fmt.Println(PadLeft("aa", "x", 2))
fmt.Println(PadLeft("abc", "xy", 3))
输出(在上尝试):


请参阅类似/相关问题:

谢谢。这就是我想要的优雅,我知道它就在那里,但我就是看不到。这大大提高了代码的性能一个数量级。在我的基准测试中填充200个字符时,它从3785 ns/op变为220 ns/op。填充4个字符时,它从196 ns变为220 ns/op/op到73.6 ns/op。这对提高我的库的性能非常有帮助。
fmt.Println(PadLeft("aa", "x", 1))
fmt.Println(PadLeft("aa", "x", 2))
fmt.Println(PadLeft("abc", "xy", 3))
xaa
xxaa
xyxyxyabc