1

String example (not necessary A and B, but not X): AAAXBBXBXBBB I want to find all occoruncaes of X and save them in an array.

I wrote a function:

val arrayList = ArrayList<Int>()
fun findAllX(str: String){
    for(i in 0 until str.length){
        if(str[i] == 'X'){
            arrayList.add(i)
        }
    }
}

Result in this example: arrayList that contains integers 3, 6, 8

Is there a better/cleaner way to write this?

GeoCap
  • 505
  • 5
  • 15

1 Answers1

1

Here is a one-liner:

"AAAXBBXBXBBB".withIndex().filter { it.value == 'X' }.map { it.index }.toTypedArray()