格式化多次出现的 Kotlin 字符串

Format Kotlin String with multiple occurrences

我有一个如下所示的字符串模板:

val template = "Something %s something else %s. The first was %1$s, the second was  %2$s"

与 Java 配合得很好。我如何在 Kotlin 中使用这个重复出现的字符串值? 看起来 %1$s 不可能。

编译器警告:unresolved reference: s

Kotlin 中的字符串文字能够进行字符串插值,美元符号是 string template expression 的开头。如果您需要字符串中的文字美元符号,则应使用反斜杠将其转义:$。所以你的模板(我假设你传递给 String.format)变成:

val template = "Something %s something else %s. The first was %1$s, the second was %2$s"

say, $ can be used for String Templates.

除了使用反斜杠对字符$进行转义外,您还可以使用${'$'}对其进行转义。当您想在不支持反斜杠转义的原始字符串中转义 $ 时,此语法将更有用。

val template = "Something %s something else %s. The first was %1${'$'}s, the second was %2${'$'}s"