You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin实现大小写翻转+对称数字互换及现有代码不生效问题求解

问题原因
  • 核心问题是你遍历了整个字符数组,对称位置的数字会被两次交换:第一次遍历左半侧索引时完成交换,等遍历到右半侧对应对称索引时,会再次触发交换逻辑把数字换回去,最终等于没有完成互换。
  • 以你示例中的5worLD6片段为例,该子串长度为7,索引0是数字5,索引6是数字6:遍历到索引0时两者会完成交换;等遍历到索引6时,计算得到的对称索引是0,此时两个位置的字符仍都是数字,会再次触发交换把两个数字换回初始状态。
修复方案

只需要调整遍历范围,仅遍历字符数组前半段的索引即可避免重复交换,修改后可运行代码如下:

val uniqueWords = str.split(" ").map { it.toCharArray() }
uniqueWords.forEach { chars ->
    // 仅遍历到数组长度的1/2位置,避免对称位置重复处理
    for (charIndex in 0 until chars.size / 2) {
        val endIndex = chars.lastIndex - charIndex
        if (chars[charIndex].isDigit() && chars[endIndex].isDigit()) {
            // 临时变量存储值完成交换
            val temp = chars[charIndex]
            chars[charIndex] = chars[endIndex]
            chars[endIndex] = temp
        }
    }
}
// 处理完成后转换为字符串列表即可使用
val mVal = uniqueWords.map { it.concatToString() }
拓展补充

如果你后续要补充大小写翻转的需求,在同一个遍历逻辑中新增非数字字符的处理分支即可,完整逻辑如下:

val uniqueWords = str.split(" ").map { it.toCharArray() }
uniqueWords.forEach { chars ->
    for (charIndex in 0 until chars.size / 2) {
        val endIndex = chars.lastIndex - charIndex
        if (chars[charIndex].isDigit() && chars[endIndex].isDigit()) {
            // 对称位置都是数字则互换
            val temp = chars[charIndex]
            chars[charIndex] = chars[endIndex]
            chars[endIndex] = temp
        } else {
            // 非数字字符翻转大小写
            chars[charIndex] = if (chars[charIndex].isUpperCase()) chars[charIndex].lowercaseChar() else chars[charIndex].uppercaseChar()
            chars[endIndex] = if (chars[endIndex].isUpperCase()) chars[endIndex].lowercaseChar() else chars[endIndex].uppercaseChar()
        }
    }
    // 处理长度为奇数的字符串中间位的大小写翻转
    if (chars.size % 2 != 0) {
        val midIndex = chars.size / 2
        chars[midIndex] = if (chars[midIndex].isUpperCase()) chars[midIndex].lowercaseChar() else chars[midIndex].uppercaseChar()
    }
}
val mVal = uniqueWords.map { it.concatToString() }

内容的提问来源于stack exchange,提问作者Taimoor Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:36:01