首页 > 解决方案 > 按顺序将映射元素添加到切片

问题描述

我正在研究文本换行功能。我希望它将一长行文本分成最大字符长度的字符串切片。我已经让它大部分工作了。但是,有时单词会乱序排列。

当一个长词后跟一个短词时,就会发生这种情况。我相信该程序看到较长的单词不适合该行,因此它会跳过该单词并添加下一个适合的单词。

由于这是文本,因此单词必须保持正确的顺序。如何强制循环仅以正确的顺序添加单词?

实际输出:

[]string{" Go back out of the hotel entrance and your is", " room on lower ground a private street", " entrance."}

预期输出:

[]string{" Go back out of the hotel entrance and your", " room is on lower ground a private street", " entrance."}

这就是我到目前为止所拥有的。

链接: https: //play.golang.org/p/YsCWoM9hQJV

package main

import (
    "fmt"
    "strings"
)

func main() {
    directions := "Go back out of the hotel entrance and your room is on the lower ground a private street entrance."

    ws := strings.Split(directions, " ")
    neededSlices := strings.Count(directions, "") / 48
    if strings.Count(directions, "")%48 != 0 {
        neededSlices++
    }
    ls := make([]string, neededSlices, neededSlices)

    keys := make(map[string]bool)
    for i := 0; i < len(ls); i++ {
        for _, v := range ws {
            if _, ok := keys[v]; !ok {
                if strings.Count(ls[i], "")+strings.Count(v, "") <= 48 {
                    ls[i] = ls[i] + " " + v
                    keys[v] = true
                }
            }
        }
    }

    fmt.Printf("%#v", ls)

}

标签: stringloopsgo

解决方案


我认为这是您需要的简单实现

package main

import (
    "fmt"
    "strings"
)

func main() {
    directions := "Go back out of the hotel entrance and your room is on the lower ground a private street entrance."

    ws := strings.Split(directions, " ")
    
    sl := []string{""}
    i := 0
    
    for _,word := range ws {
        if (len(sl[i]) + len(word) + 1) >=48 {
            i++
            sl = append(sl, "")
        }
        sl[i] += " " + word
    }
    

    fmt.Printf("%#v", sl)

}

链接: https: //play.golang.org/p/7R2TS6lv4Tm


推荐阅读