将加入的片子用定界符分割成最大N个长度的片子。

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

我有片线

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

delimiter := ";"

如果定界符长度小于或等于10,我想让它们的另一个片断连接起来。

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

"anotherverylongword "有超过10个字符,所以它是分开的,其余的少于或正好是10个字符,加上分隔符,所以它是连接的。

我用JavaScript问了同样的问题(如何将带分隔符的连接数组分割成块?)

但解决方案是在考虑到不可变性的情况下写的.围棋的本质是比较可变的,我无法绞尽脑汁把它翻译成围棋,所以才在这里问。

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

你可以试试这种方式,添加一些注释

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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.