【问题标题】:How to append 2 strings in Kotlin?如何在 Kotlin 中附加 2 个字符串?
【发布时间】:2019-01-02 06:18:30
【问题描述】:
我正在尝试连接 2 个字符串,但不知道该怎么做。
这是我的代码:
val word = R.string.word
我正在尝试在setText("$currentPage/5") 中附加"$currentPage/5"
我试图以这种方式做到这一点setText("$word $currentPage/5")
这样setText("${R.string.value} $currentPage/5")
它没有用,它只显示数字而不是文本
【问题讨论】:
标签:
android
kotlin
android-context
【解决方案1】:
In Kotlin, the concatenation of string can be done by **interpolation/templates**.
val a = "Its"
val b = "Kotlin!"
val c = "$a $b"
The output will be Its Kotlin!
Or we can alson do concatenate using the **+ / plus() operator**:
val a = "String"
val b = "Concatenate"
val c = a + b
val d =a.plus(b)
print(c)
The output will be: StringConcatenate
print(d)
The output will be: StringConcatenate
Or you can concatenate using the StringBuilder which is a normal way to do that.
【解决方案2】:
作为未来的资源并回答为什么接受的答案有效:-
String Templates:-
字符串可能包含模板表达式,即被评估的代码片段,其结果被连接到字符串中。
如何实现这些?
模板表达式应以美元符号 ($) 开头,并包含一个简单的名称:
注意:- 原始字符串和转义字符串都支持模板。
【解决方案3】:
要连接两个字符串,我们可以这样做
val concatenatedWord = "${resources.getString(R.string.value)}:
${number/3}。”
如果 R.string.value 是 "结果" 并且数字是 15,则 concatenatedWord 的值将是 "结果:5。 "
或者我们也可以使用 + 运算符或使用 StringBuilder 进行连接。
但如果你这样做
textView.text = "${resources.getString(R.string.value)}: ${number/3}."
AS会警告“不要用setText拼接显示的文本。”所以,在textview中设置拼接文本的情况下,可以考虑使用
String.format("%s: %d.", resources.getString(R.string.value):
数/3)
【解决方案4】:
尝试使用这个:
val word = getString(R.string.word)
text_view.text = "$word $currentPage/5"
如果你想编辑你的值(例如当前页面)用 {} 包装它
例如
val word = getString(R.string.word)
text_view.text = "$word ${currentPage/5}"
记得使用正确的 kotlin 语法