Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split First and Last word from string in kotlin

I have some strings that I want to split into first and last names. I tried this example. But I only want the first and last word from the string.

For example

Scenario 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val string = "Vivek Modi"

Scenario 2

val string = "Vivek  Modi "

Scenario 3 after the first name I added space

val string = "Vivek  Modi"

Scenario 4 after the last name I added space

val string = "Vivek Modi "

Scenario 5 after the last name I added space

val string = "Vivek XYZ Modi "

Expected output

firstName = Vivek

lastName = Modi

I tried this code

val displayName = "Vivek Modi "
val parts  = displayName.split(" ").toMutableList()
val firstName = parts.firstOrNull()
parts.removeAt(0)
val lastName = parts.lastOrNull()
println("*** displayName: $displayName")
println("*** firstName : $firstName")
println("*** lastName : $lastName")

Getting Output

*** displayName: Vivek Modi 
*** firstName : Vivek
*** lastName : 

Is there any better way to solve this situation. Thanks

>Solution :

You can use a regular expression for this:

fun splitName(name: String): Pair<String?, String?> {
    val names = name.trim().split(Regex("\\s+"))
    return names.firstOrNull() to names.lastOrNull()
}

The trim method removes any leading/trailing space from the string (covering scenarios 2, 4 and 5) and the split method with the regular expression \s+ splits the string by one (scenario 1) or more (scenarios 2 and 3) white spaces. Here’s some tests:

val scenarios = arrayOf("Vivek Modi", "Vivek  Modi ", "Vivek  Modi", "Vivek Modi ", "Vivek XYZ Modi ")
scenarios.forEach { input ->
    val (firstName, lastName) = splitName(input)
    assert(firstName == "Vivek")
    assert(lastName == "Modi")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading