首页 > 解决方案 > 在 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", ...)

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

通过使用joinToStringand subString,我可以达到结果。

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

问题是:我只想在迭代器达到MAX_LENGTHjoinToString时使用并中断迭代器,因此它不必执行任何“连接”,然后再进行。subString

我怎么能那样做?

标签: javaandroidlistkotlin

解决方案


首先用于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

推荐阅读