本文介绍了如何制作验证名字和姓氏输入的功能-Kotlin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个函数来验证用户是否输入了他的名字和姓氏.它接收一个字符串并返回一个布尔值.如果字符串有2个名字(名字和姓氏)并且每个名字的首字母必须大写,则返回true.我一直在努力做到这一点,但如果有人能帮助我,我将不胜感激.顺便说一句,我正在科特林这样做.

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.

我忘了提到我不能使用.split()

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

推荐答案

您应该将字符串拆分为空格,然后检查每个字母的首字母是否大写:

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() }
}

如果由于某些原因您确实不能使用splitindexOf,则只需使用循环:

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
}

这篇关于如何制作验证名字和姓氏输入的功能-Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:17