连接到中间被截断的字符串

问题描述 投票:0回答:1

如果我有一个很长的列表并且只想打印前 6 个元素,这很简单:

// Let's say list contains the first few numbers in the  Fibonacci sequence
println(list.joinToString(limit = 6)) // output: [0, 1, 1, 2, 3, 5, ...]

但我想显示前 3 个和后 3 个:

[0, 1, 1, ..., 55, 89, 144]

有没有一种巧妙的方法来使用

joinToString
来做到这一点?

我只能想到手动完成,本质上是

list.take(3) + "..." + list.takeLast(3)
,但我认为可能有更简单的方法。

kotlin collections
1个回答
0
投票

作为一个解决方案,我可以建议:

fun<T> List<T>.myJoin(leftCount: Int, rightCount: Int) = this.run{(0 until leftCount).toList() + (this.size - rightCount until this.size).toList() }.map{ this[it] }.joinToString(" ")

现在你可以使用它了:

println("1 2 5 8 9 10 31 23 1".split(" ").myJoin(3, 4))
//1 2 5 10 31 23 1
© www.soinside.com 2019 - 2024. All rights reserved.