0

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
}
user2340612
  • 10,053
  • 4
  • 41
  • 66
  • What °didn't work"? Is the result wrong, is it a compilation error (I can see a typo `inverso` instead of `inverse`), ...? – user2340612 Feb 07 '19 at 18:42
  • Ignore it, I was just translating when I posted the code. The problem that I want to solve is how can I divide for 2 the text length on for syntax... In java I did this for(int i = 0; i < texto.length()/2; i++), and I want to know how to do it on Kotlin... – Victor Harry Feb 07 '19 at 18:55
  • Of course, you don't actually need a loop at all to write this particular function; you can do it with the one-liner: `fun isPalindrome(text: String) = text == text.reversed()`.  But that wouldn't give you practice in writing loops :-) – gidds Feb 08 '19 at 00:31

1 Answers1

1

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.

user2340612
  • 10,053
  • 4
  • 41
  • 66