Parse 2D Array in Kotlin

南楼画角 提交于 2021-02-10 17:30:15

问题


I have created a 2D array named squareData as shown below:

 private lateinit var squareData: Array<Array<String>>

 squareData = Array(3, {Array(3, {""})})

Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?


回答1:


You can iterate in the array like this :

for (strings in squareData) {
    for (string in strings) {
        Your code here
    }
}

The first for iterate through the first dimension so it has string arrays and the second one through the second dimension so it has the string values




回答2:


You can use regular nested for loop.

for (arr in squareData) {
    for (s in arr) {
        println(s)
    }
}

You can iterate using forEach:

squareData.forEach { it.forEach(::println) }

or if you want index position as well, forEachIndexed:

squareData.forEachIndexed { i,it -> println(i); it.forEach(::println) } 


来源:https://stackoverflow.com/questions/47265260/parse-2d-array-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!