I'm doing a palindrome exercise and want to verify half of the string in a loop. I tried to do for ex: for(index in text.indices / 2) and didn't work
fun palindrome(text:String): Boolean {
var inverse : Int = text.length - 1
for (index in text.indices) {
if (!text[index].equals(text[inverse])) {
return false
}
inverse--
}
return true
}
The for
loop syntax in Kotlin is similar to Java's "enhanced for" loop:
for (<variable> in <expression>) {
<body>
}
where <expression>
can be "anything that provides an iterator" (from the documentation)
The Kotlin equivalent of the code you added in your comment is: for (i in 0 until text.length()/2)
. Note that until
is not a keyword but rather an infix
function and creates the range 0 .. text.length()-1
.
More on ranges here.