Android 知识

Kotlin 内置函数-joinToString

2022-05-06  本文已影响0人  zcwfeng

可读格式检索集合内容,将集合转换为字符串的函数

joinToString() 根据提供的参数从集合元素构建单个 StringjoinTo() 执行相同的操作,但将结果附加到给定的 Appendable 对象。

val numbers = listOf("one", "two", "three", "four")

println(numbers)         
println(numbers.joinToString())

val listString = StringBuffer("The list of numbers: ")
numbers.joinTo(listString)
println(listString)

result------>
[one, two, three, four]
one, two, three, four
The list of numbers: one, two, three, four

val numbers = listOf("one", "two", "three", "four")    
println(numbers.joinToString(separator = " | ", prefix = "start: ", postfix = ": end"))

result ------>
start: one | two | three | four: end

val numbers = (1..100).toList()
println(numbers.joinToString(limit = 10, truncated = "<...>"))

result ------>
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, <...>

val numbers = listOf("one", "two", "three", "four")
println(numbers.joinToString { "Element: ${it.toUpperCase()}"})

result ------>
Element: ONE, Element: TWO, Element: THREE, Element: FOUR

上一篇下一篇

猜你喜欢

热点阅读