如何在一行中使用 Kotlin 打印 String 数组的所有元素?
在本文中,我们将通过一个示例,展示如何使用 Kotlin 库类在一行中打印 String 数组的所有元素。为此,我们将使用 Kotlin 库提供的 String 函数joinToString()。
根据 Kotlin 文档,函数定义如下 -
fun <T> Array<out T>.joinToString( // the String will be separated by this separator: CharSequence = ", ", // This will be added as prefix to the String prefix: CharSequence = "", // This will be added as postfix to the String postfix: CharSequence = "", // This number of element will be printed, // the remaining elements will be denoted but truncated sequence limit: Int = -1, truncated: CharSequence = "...", //any transformation required over the String transform: ((T) -> CharSequence)? = null ): String
此函数采用多个属性以便将一个 ArrayList 转换为字符串。
示例 - 在一行中打印 String 数组的所有元素
fun main(args: Array<String>) {
val mylist = listOf("Jam", "bread", "apple", "mango")
println(
mylist.joinToString(
prefix = "[",
separator = "-",
postfix = "]",
truncated = "...",
)
)
}输出
运行后,将生成以下输出 -
[Jam-bread-apple-mango]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP