背景
这几天写代码时,正好遇到了一个需求,需要将数组按指定大小进行分隔,然后进行拼接成字符串(以逗号进行分隔)。为此有了这篇文章。
实现
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
var arr []string
for i := 0; i < 11; i++ {
str := strconv.Itoa(i)
arr = append(arr, str)
}
fmt.Println("println:", group(arr, 5))
res := group(arr, 5)
for _, v := range res {
rt := strings.Join(v, ",")
fmt.Println(rt)
}
}
// 将数组 laxiconid 按指定大小进行分隔
func group(laxiconid []string, subGroupLength int64) [][]string {
max := int64(len(laxiconid))
var segmens = make([][]string, 0)
quantity := max / subGroupLength
remainder := max % subGroupLength
i := int64(0)
for i = int64(0); i < quantity; i++ {
segmens = append(segmens, laxiconid[i*subGroupLength:(i+1)*subGroupLength])
}
if quantity == 0 || remainder != 0 {
segmens = append(segmens, laxiconid[i*subGroupLength:i*subGroupLength+remainder])
}
return segmens
}
结果:
println: [[0 1 2 3 4] [5 6 7 8 9] [10]]
0,1,2,3,4
5,6,7,8,9
10
文章也会持续更新,可以微信搜索「 迈莫coding 」第一时间阅读。