Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a list of Strings and concatenate them in Kotlin?

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"
like image 511
Sylhare Avatar asked Jun 13 '19 17:06

Sylhare


2 Answers

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"
like image 122
Sylhare Avatar answered Oct 29 '22 13:10

Sylhare


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
like image 6
HAXM Avatar answered Oct 29 '22 12:10

HAXM