需要验证循环中字符串的一半

时间:2019-02-07 17:46:49

标签: for-loop kotlin palindrome

我正在做回文练习,想在循环中验证字符串的一半。我尝试做例如: for(text.indices / 2中的索引) ,但没有用

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
}

1 个答案:

答案 0 :(得分:1)

Kotlin中的for循环语法类似于Java的"enhanced for" loop

for (<variable> in <expression>) {
    <body>
}

其中<expression>可以是“提供迭代器的任何内容”(from the documentation

您在注释中添加的代码的Kotlin等效项是:for (i in 0 until text.length()/2)。请注意,until不是关键字,而是infix function,并创建range 0 .. text.length()-1

有关范围here的更多信息。