string - 按顺序将映射元素添加到切片
问题描述
我正在研究文本换行功能。我希望它将一长行文本分成最大字符长度的字符串切片。我已经让它大部分工作了。但是,有时单词会乱序排列。
当一个长词后跟一个短词时,就会发生这种情况。我相信该程序看到较长的单词不适合该行,因此它会跳过该单词并添加下一个适合的单词。
由于这是文本,因此单词必须保持正确的顺序。如何强制循环仅以正确的顺序添加单词?
实际输出:
[]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)
}
解决方案
我认为这是您需要的简单实现
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
推荐阅读
- android - 将 Google Play 服务版本从 11.2.2 升级到 15.0.0 后应用程序崩溃
- atom-editor - 仅在 Atom 中删除文本文件的尾随空格
- javascript - 我想将一个值更新为 Javascript 中已存在键的 json 对象
- python - 使用调试控制台时出错:DeprecationWarning:自 IPython 6.0 以来,`use_readline` 参数已被弃用和忽略
- machine-learning - 从 NN 模型中提取的权重大小变得高于模型
- javascript - 根据 JavaScript HTML 和 CSS 中选中的单选按钮显示特定的 div
- angular - 如何在 Angular 4 中创建多个路由器
- php - CakePHP saveMany 内部服务器错误 500
- react-native - React-native 在入门项目中不存在捆绑 URL
- r - Shiny switchInput:在不同的计算机上呈现不同的效果