1 回答

TA贡献1862条经验 获得超7个赞
你可以试试这种方式,添加了一些评论
s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u", "kkkk"}
var res []string
var cur string
for i, e := range s {
if len(cur)+len(e)+1 > 10 { // check adding string exceed chuck limit
res = append(res, cur) // append current string
cur = e
} else {
if cur != "" { // add delimeter if not empty string
cur += ";"
}
cur += e
}
if i == len(s)-1 {
res = append(res, cur)
}
}
在这里去操场上的代码
并且更加简化
s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u", "kkkk"}
var res []string
for _, e := range s {
l := len(res)
if l > 0 && len(res[l-1])+len(e)+1 > 10 {
res = append(res, e)
} else {
if l > 0 {
res[l-1] += ";" + e
} else {
res = append(res, e)
}
}
}
- 1 回答
- 0 关注
- 152 浏览
添加回答
举报