问题
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