在 Kotlin 中将 ArrayList 转换为 String 的最佳方法 [英] Best Way to Convert ArrayList to String in Kotlin
问题描述
我在 kotlin 中有一个字符串的 ArrayList
I have an ArrayList of String in kotlin
private val list = ArrayList<String>()
我想将它转换为带有分隔符,"的String
.我知道我们可以通过循环以编程方式完成,但在其他语言中,我们有可用的映射函数,例如在 Java 中我们有
I want to convert it into String
with a separator ",". I know we can do it programatically through loop but in other languages we have mapping functions available like in java we have
StringUtils.join(list);
在 Swift 中我们有
And in Swift we have
array.joined(separator:",");
是否有任何方法可以将 ArrayList
转换为 String
Kotlin 中的分隔符?
Is there any method available to convert ArrayList
to String
with
a separator in Kotlin?
添加自定义分隔符(如-"等)怎么样?
And what about for adding custom separator like "-" etc?
推荐答案
Kotlin 有 joinToString
方法仅用于此
Kotlin has joinToString
method just for this
list.joinToString()
您可以像这样更改分隔符
You can change a separator like this
list.joinToString(separator = ":")
如果你想要更多的自定义,这些都是你可以在这个函数中使用的参数
If you want to customize it more, these are all parameters you can use in this function
val list = listOf("one", "two", "three", "four", "five")
println(
list.joinToString(
prefix = "[",
separator = ":",
postfix = "]",
limit = 3,
truncated = "...",
transform = { it.uppercase() }
)
)
哪个输出
[一:二:三:...]
[ONE:TWO:THREE:...]
这篇关于在 Kotlin 中将 ArrayList 转换为 String 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!