1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
您只能使用make()
和new()
分配已清零的緩沖區(qū)(字節(jié)片或數(shù)組)。您可以使用復(fù)合文字來(lái)獲取最初包含非零值的切片或數(shù)組,但您不能動(dòng)態(tài)描述初始值(索引必須是常量)。
從類(lèi)似但非常有效的strings.Repeat()
函數(shù)中獲取靈感。它以給定的計(jì)數(shù)重復(fù)給定的字符串:
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)
}
strings.Repeat()
進(jìn)行一次分配以獲得工作緩沖區(qū)(這將是一個(gè)字節(jié) slice?[]byte
),并使用內(nèi)置copy()
函數(shù)復(fù)制可重復(fù)的字符串。值得注意的一件事是它使用工作副本并嘗試逐步復(fù)制整個(gè)副本,這意味著例如如果字符串已被復(fù)制 4 次,則復(fù)制此緩沖區(qū)將使其成為 8 次,等等。這將最大限度地減少對(duì)copy()
.?該解決方案還利用了copy()
可以從 a 復(fù)制字節(jié)string
而無(wú)需將其轉(zhuǎn)換為字節(jié)片的優(yōu)勢(shì)。
我們想要的是類(lèi)似的東西,但我們希望將結(jié)果添加到字符串之前。
我們可以考慮到這一點(diǎn),只需分配一個(gè)內(nèi)部使用的緩沖區(qū)Repeat()
加上我們左填充的字符串的長(zhǎng)度。
結(jié)果(不檢查參數(shù)count
):
func PadLeft(s, p string, count int) string {
? ? ret := make([]byte, len(p)*count+len(s))
? ? b := ret[:len(p)*count]
? ? bp := copy(b, p)
? ? for bp < len(b) {
? ? ? ? copy(b[bp:], b[:bp])
? ? ? ? bp *= 2
? ? }
? ? copy(ret[len(b):], s)
? ? return string(ret)
}
測(cè)試它:
fmt.Println(PadLeft("aa", "x", 1))
fmt.Println(PadLeft("aa", "x", 2))
fmt.Println(PadLeft("abc", "xy", 3))
輸出(在Go Playground上嘗試):
xaa
xxaa
xyxyxyabc
- 1 回答
- 0 關(guān)注
- 145 瀏覽
添加回答
舉報(bào)