Kotlin-如何正确连接字符串 [英] Kotlin - How to correctly concatenate a String

查看:2959
本文介绍了Kotlin-如何正确连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常基本的问题,在Kotlin中连接字符串的正确方法是什么?

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

在Java中,您可以使用concat()方法,例如

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

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

concat()函数不适用于Kotlin.我应该使用+符号吗?

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

推荐答案

在Kotlin中,您可以使用

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

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

输出为:Hello World

或者您可以使用+/ plus() 运算符:

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)

输出为:HelloWorld

或者您可以使用 StringBuilder .

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)

输出为:HelloWorld

这篇关于Kotlin-如何正确连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆