java - 在 Kotlin 中添加限制 joinToString 的条件
问题描述
我有一个这样的字符串列表:
val texts = listOf("It is a",
"long established fact that a reader will be distracted,",
"by the readable content of a page when looking at its layout.",
"The point of using Lorem Ipsum is that it has a more-or-less normal",
"distribution of letters, as opposed to using, making it look like readable English.",
" Many desktop publishing packages and web page,",
"editors now use Lorem Ipsum as their default model text, and a search,",
"for \'lorem ipsum\' will uncover many web sites still in their infancy",
"Various versions have evolved over the years", ...)
我想在它们之间添加一个分隔符“”并限制结果的长度。
通过使用joinToString
and subString
,我可以达到结果。
texts.filter { it.isNotBlank() }
.joinToString(separator = " ")
.substring()
问题是:我只想在迭代器达到MAX_LENGTHjoinToString
时使用并中断迭代器,因此它不必执行任何“连接”,然后再进行。subString
我怎么能那样做?
解决方案
首先用于takeWhile
限制总长度,然后join
:
fun main(args: Array<String>) {
val texts = listOf("It is a",
"long established fact that a reader will be distracted,",
"by the readable content of a page when looking at its layout.",
"The point of using Lorem Ipsum is that it has a more-or-less normal",
"distribution of letters, as opposed to using, making it look like readable English.",
" Many desktop publishing packages and web page,",
"editors now use Lorem Ipsum as their default model text, and a search,",
"for \'lorem ipsum\' will uncover many web sites still in their infancy",
"Various versions have evolved over the years")
val limit = 130
var sum = 0
val str = texts.takeWhile { sum += it.length + 1; sum <= limit }.joinToString(" ")
println(str)
println(str.length)
}
将打印
It is a long established fact that a reader will be distracted, by the readable content of a page when looking at its layout.
125
推荐阅读
- javascript - JavaScript 运行时错误:“Microsoft”未定义 - Bing 地图版本 7
- angular - 如何使用angular2中的primeng在单击编辑按钮上为各个字段分配值
- angular - 路由器在 highcharts 中未定义
- android - Jenkins Mac Xamarin UI 测试失败
- ubuntu - KVM - 无法连接到管理程序错误
- c++ - 使用 MPI 在超立方体中广播
- c# - 从 DBPedia 服务获取信息
- vue.js - vue.js test-utils 为什么我的 onSubmit 函数 mock 没有被调用?
- python - 大型数据集上的 predict_on_batch() 内存错误
- javascript - Yargs 帮助不显示所有帮助选项