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

如何在for循环中计算字符串各字符对应的字母索引值总和

Kotlin计算字母索引总和的实现方法

你只需在for循环外部声明一个可变的累加变量,每次遍历字符时将计算得到的位置值追加到该变量即可。修改后的完整代码如下:

import java.util.Locale

fun main() {
    val name = "abc".toLowerCase(Locale.ROOT)
    var sum = 0 // 初始化总和变量为0
    for (element in name) {
        val position = element - 'a' + 1
        sum += position // 累加当前字符的位置值
    }
    println(sum) // 输入为"abc"时输出结果为6(1+2+3)
}

补充注意事项

  • 累加变量必须使用var关键字声明为可变变量,不可使用val声明的不可变变量,否则无法修改数值
  • 如果字符串可能包含非小写字母的字符,可添加判断逻辑过滤无效字符,避免计算错误:
for (element in name) {
    // 仅对a-z范围内的小写字母计算位置
    if (element in 'a'..'z') {
        val position = element - 'a' + 1
        sum += position
    }
}
  • Kotlin中也可以用内置集合函数实现更简洁的写法,无需手动写for循环:
val sum = name.sumOf { 
    if (it in 'a'..'z') it - 'a' + 1 else 0 
}

内容的提问来源于stack exchange,提问作者Web Services

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:45:03