There is such task: such fields as a name
, a surname
and a patronymic
arrive at an input.
In the simplest case, all these fields are filled with data, so their output looks like this:
"name" "surname" "patronymic"
However, there are times when, for example, the last name field is missing, so the output should look like this:
"name" "patronymic"
Another case, when there is no patronymic, in this case it should be displayed like this:
"name" "surname"
The same thing with the name
, it may be missing, how it should look, I think you already guessed it.
I understand that you most likely need to somehow use if-else
to achieve the desired result for all cases, but it seems to me, will be too much code. Is it possible to somehow solve this problem and process all the options?
CodePudding user response:
val name = "name"
val surname = "surname"
val patronymic = "patronymic"
val result = listOf(name, surname, patronymic)
.filter { it.isNotBlank() }
.joinToString(" ")
println(result)
Or with a helper function:
fun List<String>.concatWithBlank() = this.filter { it.isNotBlank() }.joinToString(" ")
val result = listOf(name, surname, patronymic).concatWithBlank()