SlowLearner
SlowLearner

Reputation: 23

How to print out every other element from String in Kotlin?

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

Answers (2)

Kent
Kent

Reputation: 195039

Update

This one-liner is better:

sve.forEachIndexed { i, v -> if (i%2==1) println(v) }

old answer below

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

Ervin Szilagyi
Ervin Szilagyi

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

Related Questions