Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...