【问题标题】:Split joined slice with delimiter into chunks of maximum N length将带分隔符的连接切片拆分为最大 N 长度的块
【发布时间】:2020-09-18 16:48:40
【问题描述】:

我有一段字符串

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

delimiter := ";"

如果分隔符长度小于或等于 10,我想加入其中的另一片

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

"anotherverylongword" 有超过 10 个字符,所以它是分开的,rest 有更少或正好 10 个字符,带有分隔符,所以它被加入了。

我用 JavaScript (How to split joined array with delimiter into chunks) 提出了同样的问题

但是在编写解决方案时考虑了不变性。 Go 的性质更易变,我无法将其转成 Go,这就是我在这里问它的原因。

【问题讨论】:

    标签: arrays go slice delimiter chunks


    【解决方案1】:

    你可以试试这个方法,添加了一些cmets

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

    代码在游乐场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)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2016-08-02
      • 1970-01-01
      • 2021-02-11
      • 2012-07-04
      • 2011-02-07
      • 2011-01-08
      相关资源
      最近更新 更多