Home > Software design >  Split First and Last word from string in kotlin
Split First and Last word from string in kotlin

Time:11-10

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

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

CodePudding user response:

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")
}
  • Related