Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Merge two strings in kotlin

I have two strings

val a = "abc"
val b = "xyz"

I want to merge it and need output like below

axbycz

I added both strings to arraylist and then flatmap it

val c = listOf(a, b)

val d = c.flatMap {
    it.toList()
}

but not getting the desired result

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Use the zip function. It creates a list of pairs with "adjacent" letters. You can then use joinToString with a transformer to create your final result.

a.zip(b) // Returns the list [(a, x), (b, y), (c, z)]
 .joinToString("") { (a, b) -> "$a$b" } // Joins the list back to a string with no separator
over 4 years ago · Santiago Trujillo Report

0

You can always use a simple loop, assuming both strings have the same size. That way You only allocate a StringBuilder and counter variable, without any lists, arrays or pairs:

val a = "abc"
val b = "xyz"
val sb = StringBuilder()
for(i in 0 until a.length){
    sb.append(a[i]).append(b[i])
}
val d = sb.toString()
over 4 years ago · Santiago Trujillo Report

0

marstran's answer is really concise and Pawels answer is really fast. Using buildString you can have to best of both worlds:

buildString {
    a.zip(b).forEach { (a, b) ->
        append(a).append(b)
    }
}

buildString creates a StringBuilder and offers it as receiver in the lambda. It returns the built string.

Try it out here: Kotlin Playground. Thanks to Pawel for creating the original benchmark.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!