我有片琴弦
s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u"}
delimiter := ";"
如果分隔符长度小于或等于10,我想再加入其中的一部分
因此输出将是:{"some;word", "anotherverylongword", "word;yyy;u"}
“” anotherverylongword“包含10个以上的字符,因此分隔开,rest包含少于10个字符或恰好有10个字符,因此将它们连接起来。
我用JavaScript(How to split joined array with delimiter into chunks)提出了同样的问题
但是解决方案在编写时牢记不变。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 {
res = append(res, cur)
cur = e
} else {
if cur != "" {
cur += ";"
}
cur += e
}
if i == len(s)-1 {
res = append(res, cur)
}
}
去游乐场的代码here