Go-使用分隔符将连接的切片分割成最大N个长度的块

问题描述 投票:0回答:1

我有片琴弦

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,这就是为什么我在这里问它的原因。

arrays go slice delimiter chunks
1个回答
0
投票

您可以尝试这种方式

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

© www.soinside.com 2019 - 2024. All rights reserved.