例如,在每 3 个字符后拆分 “helloworld” ,那么理想情况下它应该返回一个 [“hel”,”low”,”orl”,”d”] 数组

    1. func Chunks(s string, chunkSize int) []string {
    2. if len(s) == 0 {
    3. return nil
    4. }
    5. if chunkSize >= len(s) {
    6. return []string{s}
    7. }
    8. var chunks []string = make([]string, 0, (len(s)-1)/chunkSize+1)
    9. currentLen := 0
    10. currentStart := 0
    11. for i := range s {
    12. if currentLen == chunkSize {
    13. chunks = append(chunks, s[currentStart:i])
    14. currentLen = 0
    15. currentStart = i
    16. }
    17. currentLen++
    18. }
    19. chunks = append(chunks, s[currentStart:])
    20. return chunks
    21. }

    例如将 mac地址 8810893093C0 转换为 88:10:89:30:93:C0

    1. mac :="8810893093C0 "
    2. mac = strings.Join(Chunks(mac, 2), ":")

    原文 https://www.imooc.com/wenda/detail/635169