Home > Back-end >  Get the sum of numbers in a for loop
Get the sum of numbers in a for loop

Time:11-30

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     
}

CodePudding user response:

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}")

CodePudding user response:

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

  • Related