我需要将长度超过 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 }