Reputation:
Given the array below what is the simplest way to print it? Looping is one option but is there any other simpler option?
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
Upvotes: 3
Views: 514
Reputation: 9263
That depends on the way you want to show it.
fun Array.contentDeepToString: String
Returns a string representation of the contents of this array as if it is a List. Nested arrays are treated as lists too. If any of arrays contains itself on any nesting level that reference is rendered as "[...]" to prevent recursion.
Note this is an inlined function using Arrays.deepToString(array)
under the hood.
Then using array.contentDeepToString()
you get in the output this string:
[[1, 2], [3, 4], [5, 6, 7]]
I mostly use Array.joinToString
, its allow to join the array using a given separator and applying a transformation to each element. From the doc:
Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied. If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit] elements will be appended, followed by the [truncated] string (which defaults to "...")
In your case as each item of your array is a subarray, you have to apply a transformation for them also using
array.joinToString("\n") { subarray ->
subarray.joinToString()
}
This give you an output as:
1, 2
3, 4
5, 6, 7
You can play with separator, prefix, postfix, and transformation parameters to get your wanted format.
contentDeepToString
and joinToString
use for loop in their implementation, take this in consideration.joinToString
is also available for Iterable
and Sequence
Upvotes: -1
Reputation: 1505
1. Using standard library
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
print(Arrays.deepToString(array))
2. Using for loop
fun <T> print2DArray(twoDArray: Array<Array<T>>) {
for (i in 0 until twoDArray.size) {
for (j in 0 until twoDArray[i].size) {
print(twoDArray[i][j])
if (j != twoDArray[i].size - 1) print(" ")
}
if (i != twoDArray.size - 1) println()
}
}
val array = arrayOf(arrayOf(1, 2), arrayOf(3, 4), arrayOf(5, 6, 7)) print2DArray(array)
Upvotes: 1
Reputation: 30528
There is built-in functionality for this:
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
println(array.joinToString(prefix = "[", postfix = "]") {
it.joinToString(prefix = "[", postfix = "]")
})
Upvotes: 1