Home > Blockchain >  Kotlin get first character from list of strings
Kotlin get first character from list of strings

Time:12-06

I have a kotlin list of strings. I need the first characters of each string in the list and format the string the below expected way. Is there a buitin method equivalent to get first characters in the list?

fun main() {
    val stringlist = listOf("One", "Two", "Four")
    var name = "Flock"
    // Current Output Flock:One:Two:Four
    println(name   ":"  stringlist.joinToString(":"))
    // expected output Flock:O:T:F
}

CodePudding user response:

Extract the first character with map from the list:

fun main() {
  val firstCharList = listOf("One", "Two", "Four").map { it.first() }
  val name = "Flock"
  println(name   ":"   firstCharList.joinToString(":"))
}

CodePudding user response:

The last parameter of joinToString is a lambda of type (T) -> CharSequence where you can transform each element into the CharSequence that should appear in the output. So your code would become:

println(name   ":"   stringlist.joinToString(":") { it.first().toString() })

Note that first would throw in case the string is empty. If you want to avoid that you can filter out empty strings beforehand or use something like firstOrNull()?.toString().orEmpty() to transform empty strings into empty strings.

CodePudding user response:

You can also pass it.take(1) to the transform parameter of joinToString. take(n) returns the first n characters of the string. You don't need to handle any error or nullability here as take(n) returns the original string if n is greater than length of string.

println(name   ":"  stringlist.joinToString(":") { it.take(1) })

Playground

  • Related