java 如何在一行中打印 Kotlin 中字符串数组的所有元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49899665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print all elements of String array in Kotlin in a single line?
提问by Sushobh Nadiger
This is my code
这是我的代码
fun main(args : Array<String>){
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
//How do i print the elements using the print method in a single line?
}
In java i would do something like this
在java中我会做这样的事情
someList.forEach(java.lang.System.out::print);
someList.forEach(java.lang.System.out::print);
回答by Michael
Array
has a forEach
method as well which can take a lambda:
Array
也有一个forEach
可以使用 lambda 的方法:
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach { System.out.print(it) }
or a method reference:
或方法参考:
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach(System.out::print)
回答by delitescere
Idiomatically:
惯用语:
fun main(args: Array<String>) {
val someList = arrayOf("United", "Chelsea", "Liverpool")
println(someList.joinToString(" "))
}
This makes use of type inference, an immutable value, and well-defined methods for doing well-defined tasks.
这利用类型推断、不可变值和明确定义的方法来执行明确定义的任务。
The jointoString()
method also allows prefix and suffix to be included, a limit, and truncation indicator.
该jointoString()
方法还允许包含前缀和后缀、限制和截断指示符。
回答by twupack
I know three ways to do this:
我知道三种方法可以做到这一点:
(0 until someList.size).forEach { print(someList[it]) }
someList.forEach { print(it) }
someList.forEach(::print)
Hope you enjoyed it :)
希望你喜欢它:)
回答by statut
You can do the same:
你也可以做到的:
fun main(args : Array<String>){
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach(System.out::print)
}
回答by WitWicky
You can achieve this using "contentToString" method:
您可以使用“contentToString”方法实现此目的:
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
println(someList.contentToString())
O/p:
[United, Chelsea, Liverpool]e
回答by JPO
You could
你可以
fun main(args : Array<String>){
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
val sb = StringBuilder()
for (element in someList) {
sb.append(element).append(", ")
}
val c = sb.toString().substring(0, sb.length-2)
println(c)
}
gives
给
United, Chelsea, Liverpool
alternatively you can use
或者你可以使用
print(element)
in the for loop, or even easier use:
在 for 循环中,甚至更容易使用:
var d = someList.joinToString()
println(d)