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

更新日期:2022-03-01

558 次瀏覽

啟動你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.