我得找一個像這樣的字符串模板:格式字符串科特林出現多次
val template = "Something %s something else %s. The first was %1$s, the second was %2$s"
正常工作與Java。如何在Kotlin中使用此重複出現的字符串值? 看起來像%1$s
是不可能的。
編譯器警告:unresolved reference: s
我得找一個像這樣的字符串模板:格式字符串科特林出現多次
val template = "Something %s something else %s. The first was %1$s, the second was %2$s"
正常工作與Java。如何在Kotlin中使用此重複出現的字符串值? 看起來像%1$s
是不可能的。
編譯器警告:unresolved reference: s
在科特林字符串字面能夠串插,美元符號是string template expression的開始。如果您需要字符串中的字面美元符號,則應使用反斜槓將其轉義:\$
。所以,你的模板(我假設你傳遞給String.format
)變爲:
val template = "Something %s something else %s. The first was %1\$s, the second was %2\$s"
作爲Alexander Udalov's answer說,$
可用於String Templates。
除了使用反斜槓來轉義字符$
之外,還可以使用${'$'}
來轉義它。當您想要在原始字符串中轉義$
時,此語法將更加有用,其中不支持反斜槓轉義。
val template = "Something %s something else %s. The first was %1${'$'}s, the second was %2${'$'}s"