joinToString
所在位置是kotlin.sequences.joinToString
,其相關用法介紹如下。
用法:
fun <T> Sequence<T>.joinToString(
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((T) -> CharSequence)? = null
): String
從使用separator 分隔的所有元素創建一個字符串,並使用給定的prefix 和postfix(如果提供)。
如果集合可能很大,您可以指定一個非負值 limit ,在這種情況下,隻會附加第一個 limit 元素,然後是 truncated 字符串(默認為 "...")。
操作是 terminal
。
例子:
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
val numbers = listOf(1, 2, 3, 4, 5, 6)
println(numbers.joinToString()) // 1, 2, 3, 4, 5, 6
println(numbers.joinToString(prefix = "[", postfix = "]")) // [1, 2, 3, 4, 5, 6]
println(numbers.joinToString(prefix = "<", postfix = ">", separator = "•")) // <1•2•3•4•5•6>
val chars = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q')
println(chars.joinToString(limit = 5, truncated = "...!") { it.uppercaseChar().toString() }) // A, B, C, D, E, ...!
//sampleEnd
}
輸出:
1, 2, 3, 4, 5, 6 [1, 2, 3, 4, 5, 6] <1•2•3•4•5•6> A, B, C, D, E, ...!
相關用法
- Kotlin joinTo用法及代碼示例
- Kotlin js用法及代碼示例
- Kotlin associateBy用法及代碼示例
- Kotlin all用法及代碼示例
- Kotlin map用法及代碼示例
- Kotlin filterNot用法及代碼示例
- Kotlin reduceRight用法及代碼示例
- Kotlin Random.Default用法及代碼示例
- Kotlin Byte.inc用法及代碼示例
- Kotlin getValue用法及代碼示例
- Kotlin Double.dec用法及代碼示例
- Kotlin windowedSequence用法及代碼示例
- Kotlin contentToString用法及代碼示例
- Kotlin groupByTo用法及代碼示例
- Kotlin commonPrefixWith用法及代碼示例
- Kotlin MatchResult.Destructured用法及代碼示例
- Kotlin Delegates.notNull用法及代碼示例
- Kotlin ifBlank用法及代碼示例
- Kotlin filterNotTo用法及代碼示例
- Kotlin getOrPut用法及代碼示例
- Kotlin Triple.<init>用法及代碼示例
- Kotlin Duration.toString用法及代碼示例
- Kotlin windowed用法及代碼示例
- Kotlin indexOf用法及代碼示例
- Kotlin reduceIndexed用法及代碼示例
注:本文由純淨天空篩選整理自kotlinlang.org大神的英文原創作品 kotlin.sequences.joinToString。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。