我正在做回文练习,想在循环中验证字符串的一半。我尝试做例如: 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
}
答案 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的更多信息。