登录
首页 >  Golang >  Go问答

将长文本按空格分割成字符串数组,并限制长度为 500字符

来源:stackoverflow

时间:2024-03-13 11:27:27 231浏览 收藏

哈喽!今天心血来潮给大家带来了《将长文本按空格分割成字符串数组,并限制长度为 500字符》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我需要将长度超过 500 个字符的文本拆分为多个数组。完整的任务听起来像这样:

消息被分为 500 个字符的块。如果消息超过500个字符,则从500个字符开始查找空格,如果找到空格,则在该处将消息分成几部分。如果没有找到空格,那么我们将消息除以 500 个字符。

我的决定,这只是一个开始。 我们使用正则表达式分割文本,然后通过循环将数据添加到字符串(如果长度允许)。 但我想我很困惑,如何获取字符串数组,以便每个字符串的长度最多为 500 个字符?

re := regexp.MustCompile(`\s+`)
res := re.Split(str, -1)

size := 500

finalString := ""
for i, _ := range res {
    if len(finalString+" "+res[i]) <= size {
        if len(finalString) == 0 {
            finalString += res[i]
        }
        finalString += " " + res[i]
    } else {
        break // can be added to a new line, and if the length is longer, I do not know what to do
    }
}

正确答案


为了确保我正确理解这一点,您是否希望在每 500 个字符后的第一个空格处分割文本?

请记住,字符串连接可能相对昂贵(在字符串末尾添加两个字符,如 finalstring += " " + res[i] 会产生 o(n) 复杂度,因为字符串的底层字节数组必须是已复制。

更好的解决方案是依赖bytes.buffer。我编写了这个示例代码(请注意,您可以更改 splitlength — 我不想在此处粘贴 500 个字符的输入)。

package main

import (
    "bytes"
    "fmt"
)

func main() {
    prettyPrint(split([]byte("1234567 123 12345 1234567"), 5))
}

func prettyPrint(b [][]byte) {
    for _, a := range b {
        fmt.Println(string(a))
    }
}

func split(b []byte, splitLength int) [][]byte {
    current := new(bytes.Buffer)
    var bSlice [][]byte
    counter := 0
    shouldTerminate := false

    for i, c := range b {
        if shouldTerminate == true && c == byte(32) {
            counter = 0
            shouldTerminate = false

            bSlice = append(bSlice, current.Bytes())
            current = new(bytes.Buffer)

            continue
        }

        counter++
        current.Write([]byte{c})

        if counter > splitLength {
            shouldTerminate = true
        }

        if i == len(b)-1 {
            bSlice = append(bSlice, current.Bytes())
        }
    }

    return bSlice
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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