Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to make a function that verifies if the user writes his first and last name. It receives a string and returns a boolean. It returns true if the string has 2 names(first and last) and the first letter of each name has to be capitalized. I′ve been trying to make it but havent been able to do it, if anyone could help me i′d apreciate it. btw i′m doing this in kotlin.

edit: I forgot to mention that i can′t use .split()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
416 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...