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



我有一段字符串

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

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

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

"另一个非常长的词"有超过 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)
}
}

代码在去游乐场在这里

而且更简化

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

最新更新