简体   繁体   中英

Get the sum of numbers in a for loop

I'm trying to get position value of a string. This works well by printing the integer value of each.

How do I get the sum of the alphabet index in the for loop

val name = "abc".toLowerCase(Locale.ROOT)
for (element in name) {
    val position = element - 'a' + 1     
}

Have a variable that you can just add each index to.

val input = "abc".toLowerCase(Locale.ROOT)
val alphabet = "abcdefghijklmnopqrstuvwxyz"
var sum = 0
for (element in input) {
    sum += alphabet.indexOf(element)
    Log.d("TAG", "${alphabet.indexOf(element) + 1}")
}
Log.d("TAG", "${sum}")

You can achieve that in a really concise way with the sumBy function:

val input = "abc".toLowerCase(Locale.ROOT)
val alphabet = "abcdefghijklmnopqrstuvwxyz"
val sum = input.sumBy { element ->
    Log.d("TAG", "${alphabet.indexOf(element) + 1}")
    alphabet.indexOf(element)
}

Edit (after question changed):

val name = "abc".toLowerCase(Locale.ROOT)
val sum = name.sumBy { element ->
    element - 'a' + 1     
}

Try it out here

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