求助:如何在Kotlin中打印数组的交替元素
在Kotlin中获取并打印数组的交替元素
这里有几种简洁的方法可以实现从数组中提取并打印奇数位置(从第一个元素开始)的交替元素:
方法1:使用带步长的索引遍历
直接通过索引遍历,步长设为2,每次跳过一个元素:
val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) for (i in numbers.indices step 2) { print("${numbers[i]} ") } // 输出结果:1 3 5 7 9
方法2:用filterIndexed过滤元素
利用filterIndexed根据索引筛选符合条件的元素,再用joinToString格式化输出:
val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) val alternateElements = numbers.filterIndexed { index, _ -> index % 2 == 0 } println(alternateElements.joinToString(", ")) // 输出结果:1, 3, 5, 7, 9
方法3:使用序列的step函数
将数组转为序列后调用step(2),高效跳过元素并遍历:
val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) numbers.asSequence().step(2).forEach { print("$it ") } // 输出结果:1 3 5 7 9
扩展:提取从第二个元素开始的交替元素
如果需要获取偶数位置的元素(比如2,4,6,8),只需调整索引条件:
- 遍历方式:
for (i in 1 until numbers.size step 2) - 过滤方式:
filterIndexed { index, _ -> index % 2 == 1 } - 序列方式:
numbers.asSequence().drop(1).step(2)
内容的提问来源于stack exchange,提问作者Saneer Sha
相关产品推荐
相关产品推荐

