代码之家  ›  专栏  ›  技术社区  ›  nhp

在Kotlin中添加限制joinToString的条件

  •  2
  • nhp  · 技术社区  · 7 年前

    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 subString ,我可以达到这个效果。

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

    连接管柱 仅当迭代器到达 所以它不需要做任何“连接”和 之后。

    我怎么能这么做?

    2 回复  |  直到 7 年前
        1
  •  3
  •   forpas    7 年前

    首次使用 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
    
        2
  •  2
  •   Ruwanka De Silva    7 年前

    使用 limit joinToString

    val substring = texts.filter { it.isNotBlank() }
                    .joinToString(separator = " ", limit = 10, truncated = "")
                    .substring(0)
    

    truncated 要避免的参数 ...

    既然原来的答案在寻找 MAX_LENGTH 因为上面的最终字符串长度解决方案不起作用。理想的是 takeWhile 如公认的答案。但它需要依赖外部变量。如果可能的话,我宁愿使用函数方法,但似乎没有。所以基本上我们需要使用谓词减少操作,所以稍微修改了 reduce 行得通

    public inline fun <S, T : S> Iterable<T>.reduceWithPredicate(operation: (acc: S, T) -> S, predicate: (S) -> Boolean): S {
            val iterator = this.iterator()
            if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
            var accumulator: S = iterator.next()
            while (iterator.hasNext() && predicate(accumulator)) {
                accumulator = operation(accumulator, iterator.next())
            }
            return accumulator
        }
    

    因为我们处理的是字符串连接,并试图限制其长度,所以我们必须使用 substring 花时间 花时间

    val joinedString = texts.filter { it.isNotBlank() }
                    .reduceWithPredicate({ s1, s2 -> "$s1 $s2" }, { it.length < 100 })
                    .substring(100)
    assertTrue { joinedString.length < 100 }