将带分隔符的连接切片拆分为最大 N 长度的块

Split joined slice with delimiter into chunks of maximum N length

我有一段字符串

s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u"}

delimiter := ";"

如果分隔符长度小于或等于 10,我想将它们的另一部分连接起来

所以输出将是: {"some;word", "anotherverylongword", "word;yyy;u"}

"anotherverylongword" 多于 10 个字符,因此将其分开,其余少于或恰好 10 个字符带分隔符,因此将其连接。

我和 JavaScript ()

问了同样的问题

但解决方案是在考虑不可变性的情况下编写的。 Go 的本质是更易变的,我不能绕着脑袋把它翻译成 Go,这就是为什么我在这里问它。

你可以这样试试,有评论补充

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)
    }
}

go playground 上的代码here

更简单

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)
        }
    }
}