登录
首页 >  Golang >  Go问答

将带有分隔符的连接字符串划分成最大长度为 N 的片段

来源:stackoverflow

时间:2024-02-28 09:57:23 205浏览 收藏

从现在开始,努力学习吧!本文《将带有分隔符的连接字符串划分成最大长度为 N 的片段》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我有一段字符串

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

delimiter := ";"

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

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

“anotherverylongword”超过 10 个字符,因此被分隔开,其余字符少于或正好 10 个字符,并带有分隔符,因此被连接。

我用 javascript 问了同样的问题(how to split join 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 { // 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)
    }
}

go 演示代码 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)
        }
    }
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将带有分隔符的连接字符串划分成最大长度为 N 的片段》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>