Reputation: 23
This is my code:
fun main(args:Array<String>) {
val message = "AL:OK:XX:XX:XX:XX:XX:YY~~TYPE:3~~FOF:v1.0~~RSSI:-68~~PORT:8215~~TEMP:34.22~~CH1:OK~~CH2:KS~~CH3:PR~~CH4:VL~~CH5:KS~~CH6:OK~~AUX1:OK~~AUX2:KS~~AUX3:OK"
val messagetext: String = message.replace("AL:", "")
val sve = messagetext.split("~~")
var drugi = 0
for (par in sve) {
if () {
println(par)
}
}
}
My problem is that in this if()
statement: I need to write a code, that has to print out every second element from this string (message).
Even if I get a longer String in a message or in another order, code still needs to print out every second element.
In this case this should be the output:
TYPE:3
RSSI:-68
TEMP:34.22
CH2:KS
CH4:VL
CH6:OK
AUX2:KS
How can I achieve this output?
Upvotes: 1
Views: 2834
Reputation: 195039
This one-liner is better:
sve.forEachIndexed { i, v -> if (i%2==1) println(v) }
You can use the filterIndexed function.
Replace your for
loop together with the if
inside with this:
sve.filterIndexed { index, _ -> index % 2 == 1 }.forEach{println(it)}
Upvotes: 2
Reputation: 16775
Kotlin has very verbose for loops. We can do something like this:
for (i in 1 until sve.size step 2) {
println(sve[i])
}
Upvotes: 4