I want to take first character from firstName and ...
# android
v
I want to take first character from firstName and lastName. Also firstName and lastName may be null. I want to ask is there better way to approach this? firstName :
Vivek
or
Dr. Vivek
lastName
Modi
Copy code
private fun getInitials(firstName: String?, lastName: String?): String {
    var initials = ""
    if (firstName != null && firstName.isNotEmpty()) {
        initials += firstName.take(1)
    }
    if (lastName != null && lastName.isNotEmpty()) {
        initials += lastName.take(1)
    }
    return initials
}
For example
Vivek Modi
output
VM
but when i enter
Dr. Vivek Modi
i want
VM
g
I'd make the title (Dr.) as an independent string too (it's not part of the firstname nor the lastname), and not even required to pass this title in this method. I suppose you can also reduce the code (not fully tested):
private fun getInitials(firstName: String?, lastName: String?) =
(firstName ?: "").take(1) + (lastName ?: "").take(1)
w
Maybe something like this?
Copy code
@Test
    fun asas() {
        fun getInitials(firstName: String?, lastName: String?): String {
            val first = firstName?.substringAfter(".")?.trim()?.getOrNull(0) ?: ""
            val second = lastName?.trim()?.getOrNull(0) ?: ""
            return "$first$second"
        }
        assertEquals("VM", getInitials("Vivek", "Modi"))
        assertEquals("V", getInitials("Vivek", null))
        assertEquals("V", getInitials("Vivek", ""))
        assertEquals("V", getInitials("Vivek", " "))
        assertEquals("VM", getInitials("Dr. Vivek", "Modi"))
        assertEquals("V", getInitials("Dr. Vivek", null))
        assertEquals("V", getInitials("Dr. Vivek", ""))
        assertEquals("V", getInitials("Dr. Vivek", " "))
        assertEquals("M", getInitials(null, "Modi"))
        assertEquals("M", getInitials("", "Modi"))
        assertEquals("M", getInitials(" ", "Modi"))
    }
It is assuming all person’s title would have a
.
like
Mr.
for example.
g
To detect the title, I'd use a list of all variation of titles you want to handle ("Pr.", "Pr", "Dr.", ...)
val titles = listOf("Dr", "Dr.", ...) fun extractTitle(firstName: String):String { titles.forEach { if (firstName.startsWith(it) return@extractTitle it } return "" } Just to have a draft to start from
v
@Grégory Lureau thanks i'll try this
g
Also not sure it's really related to Android 😄 maybe more getting-started for basic kotlin usage.
v
no worries it's related to android + kotlin
g
You're in #android room here, it's not Android related.
v
it's related both
🙅 1
a
344 Views