validate names in kotlin

喜你入骨 提交于 2021-02-11 12:22:01

问题


My problem is the user insert a name like "Jon Snow" and I don't know how to validate with a function if the names first char is upper case and if they are spare by a space

fun checkName(nome:String):Boolean{
    if (name[0].isUpperCase()){
        var count=0
        //if (nome)
        do {
            count++

        }while (name[count]==' ')
        var charAfterSpace:Char=nome[count]+1
        when(charAfterSpace.isUpperCase()){
           false->return false
            //else->return true
        }
    }
    return false
}

回答1:


Split the string then check if all the elements match the criteria:

fun checkName(name: String): Boolean =
    name.split(' ').all { it[0].isUpperCase() }

If double-spaces might be an issue, then first check to make sure it's not empty:

fun checkName(name: String): Boolean =
    name.split(' ').all { !it.isEmpty() && it[0].isUpperCase() }


来源:https://stackoverflow.com/questions/65162915/validate-names-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!