gpt4 book ai didi

string - 拆分文本并按空格获取字符串数组,如果文本长度超过 500,则获取字符串数组

转载 作者:行者123 更新时间:2023-12-05 05:29:48 25 4
gpt4 key购买 nike

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

消息被分成 500 个字符的 block 。如果消息超过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
}

关于string - 拆分文本并按空格获取字符串数组,如果文本长度超过 500,则获取字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74850202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com