例如,在每 3 个字符后拆分 “helloworld” ,那么理想情况下它应该返回一个 [“hel”,”low”,”orl”,”d”] 数组
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
}
例如将 mac地址 8810893093C0
转换为 88:10:89:30:93:C0
mac :="8810893093C0 "
mac = strings.Join(Chunks(mac, 2), ":")