reverseCase along with swap Integer in kotlin



我正在尝试编写一个有效的代码来逆转kotlin中的Case。

HeLLo 5worLD6->hEllO 6WORld55和6是交换的,因为它们具有相等的差

最初我试图交换数字,但forEachIndex在我现有的列表中没有改变。为什么?

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//但它不交换整数

这是您的问题:

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

您正在迭代每个单词的每个字符/索引,而endIndex是镜像偏移量,对吗?随着charIndex从开始移动到结束,endIndex从结束移动到开始。

因此,在第一次迭代中,charIndex=0endIndex=(6-0(=6。这两个指数都有数字,所以它们可以互换。阵列现在包含6WORld5

在上一次迭代中,charIndex=6endIndex=(6-6(=0。这两个指数都有数字,所以它们(再次(互换。阵列返回5WORld6

每一次交换都会发生两次,因为每对索引都会被检查两次-一次是charIndex指向下一个索引,另一次是endIndex指向它。如果你想象你想发生什么,可能更像是两端向中间移动,然后停在那里,对吧?

最新更新