Kotlin - How to correctly concatenate a String

StringKotlin

String Problem Overview


A very basic question, what is the right way to concatenate a String in Kotlin?

In Java you would use the concat() method, e.g.

String a = "Hello ";
String b = a.concat("World"); // b = Hello World

The concat() function isn't available for Kotlin though. Should I use the + sign?

String Solutions


Solution 1 - String

String Templates/Interpolation

In Kotlin, you can concatenate using String interpolation/templates:

val a = "Hello"
val b = "World"
val c = "$a $b"

The output will be: Hello World

Or you can concatenate using the StringBuilder explicitly.

val a = "Hello"
val b = "World"

val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()

print(c)

The output will be: HelloWorld

New String Object

Or you can concatenate using the + / plus() operator:

val a = "Hello"
val b = "World"
val c = a + b   // same as calling operator function a.plus(b)

print(c)

The output will be: HelloWorld

  • This will create a new String object.

Solution 2 - String

kotlin.String has a plus method:

a.plus(b)

See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/plus.html for details.

Solution 3 - String

I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.

// A list may come from an API JSON like
{
   "names": [
      "Person 1",
      "Person 2",
      "Person 3",
         ...
      "Person N"
   ]
}
var listOfNames = mutableListOf<String>() 

val stringOfNames = listOfNames.joinToString(", ") 
// ", " <- a separator for the strings, could be any string that you want

// Posible result
// Person 1, Person 2, Person 3, ..., Person N

This is useful for concatenating list of strings with separator.

Solution 4 - String

Yes, you can concatenate using a + sign. Kotlin has string templates, so it's better to use them like:

var fn = "Hello"
var ln = "World"

"$fn $ln" for concatenation.

You can even use String.plus() method.

Solution 5 - String

Similar to @Rhusfer answer I wrote this. In case you have a group of EditTexts and want to concatenate their values, you can write:

listOf(edit_1, edit_2, edit_3, edit_4).joinToString(separator = "") { it.text.toString() }

If you want to concatenate Map, use this:

map.entries.joinToString(separator = ", ")

To concatenate Bundle, use

bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }

It sorts keys in alphabetical order.

Example:

val map: MutableMap<String, Any> = mutableMapOf("price" to 20.5)
map += "arrange" to 0
map += "title" to "Night cream"
println(map.entries.joinToString(separator = ", "))

// price=20.5, arrange=0, title=Night cream

val bundle = bundleOf("price" to 20.5)
bundle.putAll(bundleOf("arrange" to 0))
bundle.putAll(bundleOf("title" to "Night cream"))
val bundleString =
    bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }
println(bundleString)

// arrange=0, price=20.5, title=Night cream

Solution 6 - String

Try this, I think this is a natively way to concatenate strings in Kotlin:

val result = buildString{
    append("a")
    append("b")
}

println(result)

// you will see "ab" in console.

Solution 7 - String

There are various way to concatenate strings in kotlin Example -

a = "Hello" , b= "World"
  1. Using + operator a+b

  2. Using plus() operator

    a.plus(b)

Note - + is internally converted to .plus() method only

In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder

StringBuilder str = StringBuilder("Hello").append("World")

Solution 8 - String

yourString += "newString"

This way you can concatenate a string

Solution 9 - String

I suggest if you have a limited and predefined set of values then the most efficient and readable approach is to use the String Template (It uses String Builder to perform concatination).

val a = "Hello"
val b = "World"
val c = "$a  ${b.toUpperCase()} !"

println(c) //prints: Hello  WORLD !

On the other hand if you have a collection of values then use joinToString method.

val res = (1..100).joinToString(",")
println(res) //prints: 1,2,3,...,100

I believe that some suggested solutions on this post are are not efficient. Like using plus or + or creating a collection for a limited set of entris and then applying joinToString on them.

Solution 10 - String

If you have an object and want to concatenate two values of an object like

data class Person(
val firstName: String,
val lastName: String
)

Then simply following won't work

val c = "$person.firstName $person.lastName"

Correct way in this case will be

"${person.firstName} ${person.lastName}"

If you want any string in between concatenated values, just write there without any helper symbol. For example if I want "Name is " and then a hyphen in between first and last name then

 "Name is ${person.firstName}-${person.lastName}"

Solution 11 - String

The most simplest way so far which will add separator and exclude the empty/null strings from concatenation:

val finalString = listOf(a, b, c)
    .filterNot { it.isNullOrBlank() }
    .joinToString(separator = " ")

Solution 12 - String

In Kotlin we can join string array using joinToString()

val tags=arrayOf("hi","bye")

val finalString=tags.joinToString (separator = ","){ "#$it" }

Result is :

> #hi,#bye


if list coming from server

var tags = mutableListOf<Tags>() // list from server

val finalString=tags.joinToString (separator = "-"){ "#${it.tagname}" }

Result is :

> #hi-#bye

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanieleView Question on Stackoverflow
Solution 1 - StringAvijit KarmakarView Answer on Stackoverflow
Solution 2 - StringHarald GliebeView Answer on Stackoverflow
Solution 3 - StringRhusferView Answer on Stackoverflow
Solution 4 - StringTusharView Answer on Stackoverflow
Solution 5 - StringCoolMindView Answer on Stackoverflow
Solution 6 - StringChinese CatView Answer on Stackoverflow
Solution 7 - StringShradha SangtaniView Answer on Stackoverflow
Solution 8 - StringKanagalingamView Answer on Stackoverflow
Solution 9 - StringMr.QView Answer on Stackoverflow
Solution 10 - StringSourab SharmaView Answer on Stackoverflow
Solution 11 - StringYasir AliView Answer on Stackoverflow
Solution 12 - StringBhavin PatelView Answer on Stackoverflow