问题描述
我在Kotlin中有一个String的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中我们有
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.toUpperCase() })
)
输出
这篇关于在Kotlin中将ArrayList转换为字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!