如何在一行中使用 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