3 回答

TA貢獻1799條經驗 獲得超9個贊
這是另一個變體游樂場。與其他答案相比,它在速度和內存方面的效率要高得多。如果您想在這里運行基準測試,它們就是benchmarks。一般來說,它比以前的版本快 5 倍,無論如何都是最快的答案。
func Chunks(s string, chunkSize int) []string {
if len(s) == 0 {
return nil
}
if chunkSize >= len(s) {
return []string{s}
}
var chunks []string = make([]string, 0, (len(s)-1)/chunkSize+1)
currentLen := 0
currentStart := 0
for i := range s {
if currentLen == chunkSize {
chunks = append(chunks, s[currentStart:i])
currentLen = 0
currentStart = i
}
currentLen++
}
chunks = append(chunks, s[currentStart:])
return chunks
}
請注意,索引指向迭代字符串時符文的第一個字節。符文占用 1 到 4 個字節。切片還將字符串視為字節數組。
以前的較慢算法
代碼在這里操場。從字節到符文再到字節的轉換實際上需要很多時間。所以最好使用答案頂部的快速算法。
func ChunksSlower(s string, chunkSize int) []string {
if chunkSize >= len(s) {
return []string{s}
}
var chunks []string
chunk := make([]rune, chunkSize)
len := 0
for _, r := range s {
chunk[len] = r
len++
if len == chunkSize {
chunks = append(chunks, string(chunk))
len = 0
}
}
if len > 0 {
chunks = append(chunks, string(chunk[:len]))
}
return chunks
}
請注意,這兩種算法以不同的方式處理無效的 UTF-8 字符。當第二個用utf8.RuneError符號 ( '\uFFFD')替換它們時,第一個按原樣處理它們,該符號在 UTF-8 中具有以下十六進制表示:efbfbd。
- 3 回答
- 0 關注
- 520 瀏覽
添加回答
舉報