简体   繁体   中英

reverseCase along with swap Integer in kotlin

I am trying to write an effective code to reverse Case in kotlin.

HeLLo 5worLD6 -> hEllO 6WORld5 5 and 6 are swap as they have equal difference

Initially I am trying to swap digit's but forEachIndex doesn't change in my existing list. Why?

val uniqueWords = str.split(" ").map { it.toCharArray() }
    uniqueWords.forEachIndexed { index, chars ->
        chars.forEachIndexed { charIndex, c ->
            val endIndex = chars.lastIndex - charIndex
            if(c.isDigit() && chars[endIndex].isDigit()){
                chars[charIndex] = chars[endIndex]
                chars[endIndex] = c
            }
        }
    }

val mVal = uniqueWords // but it doesn't swap integers

Here's your problem:

chars.forEachIndexed { charIndex, c ->
    val endIndex = chars.lastIndex - charIndex

You're iterating over each char/index of each word, and endIndex is a mirror offset right? As charIndex moves from the start to the end, endIndex moves from the end to the start.

So on the first iteration, charIndex = 0 and endIndex = (6 - 0) = 6 . Those indices both have digits, so they swap. The array now holds 6WORld5

On the last iteration, charIndex = 6 and endIndex = (6 - 6) = 0 . Those indices both have digits, so they swap (again). The array is back to 5WORld6

Every swap is gonna happen twice, because each pair of indices will be checked twice - once with charIndex pointing at the lower index, and once with endIndex pointing at it. If you visualise what you want to happen, it's probably more like the two ends moving towards the middle, and stopping there, right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM