You should split the string on spaces then check if the first letter is capitalized for each one:
fun checkName(name: String): Boolean {
val names = name.split(' ')
return names.size == 2 && names.all { it[0].isUpperCase() }
}
If you really can't use split
or indexOf
for some reason, then just use a loop:
fun checkName(name: String): Boolean {
if (name.length == 0 || !name[0].isUpperCase()) {
return false
}
var spaces = 0
for (i in 0 until name.length) {
if (name[i] == ' ') {
spaces += 1
if (spaces > 1 || !name[i + 1].isUpperCase()) {
return false
}
}
}
return true
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…