存储这样的String网格的最佳数据结构是什么?如何将String简洁地转换为该数据类型?"""10 15 20 11
14 19 04 10
18 63 92 68"""
我想通过使用一对坐标轻松访问网格中的任何数字。
最佳答案
您可以使用以下列表的list:
val grid: List<List<String>> = listOf(
listOf("10", "15", "20"),
listOf("14", "19", "04"),
listOf("18", "63", "92")
)
val elem = grid[1][1]
您还可以编写自己的extension function并将其与pairs结合使用:
fun List<List<String>>.get(i: Pair<Int, Int>) = this[i.first][i.second]
val element = grid.get(1 to 1)
更新
您可以使用此辅助程序扩展功能从字符串创建列表列表:
fun String.asGrid(size: Int): List<List<String>> = split(" ", "\n").chunked(size)
在这种情况下,首先我们将字符串split分开以获取数字并获取字符串
List<String>
的集合。在此之后,我们chunk此列表以获取List<List<String>>
用法:
val grid = """10 15 20 11
14 19 04 10
18 63 92 68""".asGrid(4)
关于kotlin - 在Kotlin中存储String网格的最佳数据结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62277382/