把字段串分割成指定长度的字符串组 [ golang ]

package main

import "fmt"

func main() {
	fmt.Println(split("abcdefghijklmnopqrstuvwxyz123", 3))
}

func split(s string, l int) []string {
	if l <= 0 {
		return []string{s}
	}
	ol := len(s)
	if ol <= l {
		return []string{s}
	}
	tmp := []string{}
	var i int
	for i = 1; i <= ol/l; i++ {
		tmp = append(tmp, s[(i-1)*l:(i-1)*l+l])
	}
	if ol%l != 0 {
		tmp = append(tmp, s[(ol/l*l):])
	}
	return tmp
}

结果:

[abc def ghi jkl mno pqr stu vwx yz1 23]

你可能感兴趣的:(golang,开发语言)