一个非常基本的问题,在 Kotlin 中连接字符串的正确方法是什么?
在 Java 中,您将使用 concat()
方法,例如
String a = "Hello ";
String b = a.concat("World"); // b = Hello World
concat()
函数虽然不适用于 Kotlin。我应该使用 +
符号吗?
最佳答案
在 Kotlin 中,您可以使用 String interpolation/templates 进行连接:
val a = "Hello"
val b = "World"
val c = "$a $b"
输出将是:Hello World
StringBuilder
对于 String templates 这是内存方面最有效的方法,因为 +
/plus()
creates new String objects 。或者您可以使用 StringBuilder
进行连接明确的。
val a = "Hello"
val b = "World"
val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()
print(c)
输出将是:HelloWorld
或者您可以使用 +
/plus()
连接运营商:
val a = "Hello"
val b = "World"
val c = a + b // same as calling operator function a.plus(b)
print(c)
输出将是:HelloWorld
https://stackoverflow.com/questions/44188240/
相关文章:
kotlin - Kotlin 中 ArrayList
kotlin - 如何在 kotlin 中检查 "instanceof "类?
java - 如何仅通过提供大小来像在 Java 中一样在 Kotlin 中创建数组?
kotlin - 我们何时应该在 Kotlin 上使用 run、let、apply、also 和 w
java - 如何在 Kotlin 中创建匿名接口(interface)的实例?
android-studio - 用于使用 gradle (1.1.2-5) 构建的 kotlin