1

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?

2 Answers 2

4

Kotlin has very verbose for loops. We can do something like this:

for (i in 1 until sve.size step 2) {
    println(sve[i])
}
Sign up to request clarification or add additional context in comments.

Comments

2

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)}

3 Comments

This is very fun approach! and it works pretty well. Thank you. Can I ask you another question regarding this? Is it possible to adjust that code so it prints out "odd" next to every first element and "even" next to every second element?
@SlowLearner you are welcome. I'm not sure if I understood you right, but give this a try: sve.forEachIndexed { i, v -> println("${if (i % 2 == 0) "even " else "odd "}$v") }
Yes you understood it perfectly. Thank you very much sir!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.