gpt4 book ai didi

java - 在 Kotlin 中添加限制 joinToString 的条件

转载 作者:搜寻专家 更新时间:2023-11-01 07:42:17 27 4
gpt4 key购买 nike

我有一个这样的字符串列表:

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", ...)

我想在它们之间添加一个分隔符"" 并限制结果的长度。

通过使用 joinToStringsubString,我可以实现结果。

texts.filter { it.isNotBlank() }
.joinToString(separator = " ")
.substring()

问题是:我只想使用 joinToString 并在迭代器到达 MAX_LENGTH 时中断迭代器,因此它不必执行任何“连接”和 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

关于java - 在 Kotlin 中添加限制 joinToString 的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919771/

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