[Solved] How to make function that validates first and last name input – Kotlin


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
}

5

solved How to make function that validates first and last name input – Kotlin