I have a list of strings such as:
listOf("1", "2", "3", "4", "+", "3")
And I want to concatenate so that I only get the numbers: "1234"
. I first attempted using a for loop which worked.
However I was wondering if Kotlin had a way of one lining the whole thing using a nice one line like:
val myList = listOf("1", "2", "3", "4", "+", "3")
someConcatenationFunction(myList) // returns "1234"
The solution I have found is this (to be put like in a separate file):
fun List<String>.concat() = this.joinToString("") { it }.takeWhile { it.isDigit() }
So basically, what it does is:
joinToString("")
: JoinToString
joins the content of a list to a String, the ""
specifies that you don't want any separators in the concatenated String.{ it }.takeWhile { it.isDigit() }
: means that from the concatenated list, I only want the Chars that are digits. takeWhile
will stop at first non digit.And here you go! Now you can simply do:
listOf("1", "2", "3", "4", "+", "3").concat() // returns "1234"
Just using function joinToString()
conact all the list items applicable for both Char
and String
.
below is the eg.
val list = listOf("1", "2", "3", "4", "+", "5")
val separator = ","
val string = list.joinToString(separator)
println(string) //output: 1,2,3,4,+,5
Other eg.
val list = listOf("My", "Name", "is", "Alise")
val separator = " "
val string = list.joinToString(separator)
println(string) //outeput: My Name is Alisse
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With