Kotlin - How to correctly concatenate a String

2019-03-22 18:37发布

问题:

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?

回答1:

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 + / 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

Or you can concatenate using the StringBuilder.

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



回答2:

kotlin.String has a plus method:

a.plus(b)

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



回答3:

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
{
   "persons": {
      "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.



回答4:

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.



回答5:

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() }


标签: string kotlin