Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

字符串模板

字符串模板是一种以编程方式生成 String 的方法。

如果在标识符名称前面放置 $,字符串模板将会将该标识符的内容插入到字符串中:

// StringTemplates/StringTemplates.kt

fun main() {
  val answer = 42
  println("Found $answer!")     // [1]
  println("printing a $1")      // [2]
}
/* 输出:
Found 42!
printing a $1
*/
  • [1] $answer 替换为 answer 的值。
  • [2] 如果 $ 后面的内容不能被识别为程序标识符,什么特殊的事情都不会发生。

你也可以使用连接(+)将值插入到 String 中:

// StringTemplates/StringConcatenation.kt

fun main() {
  val s = "hi\n" // \n 是换行字符
  val n = 11
  val d = 3.14
  println("first: " + s + "second: " +
    n + ", third: " + d)
}
/* 输出:
first: hi
second: 11, third: 3.14
*/

将表达式放在 ${} 中会对其进行求值。返回值会被转换为一个 String 并插入到结果字符串中:

// StringTemplates/ExpressionInTemplate.kt

fun main() {
  val condition = true
  println(
    "${if (condition) 'a' else 'b'}")  // [1]
  val x = 11
  println("$x + 4 = ${x + 4}")
}
/* 输出:
a
11 + 4 = 15
*/
  • [1] if(condition) 'a' else 'b' 被求值,结果被替换整个 ${} 表达式。

当一个 String 必须包含特殊字符(如引号)时,你可以使用 \反斜杠)对该字符进行转义,或者使用三引号的字符串字面值:

// StringTemplates/TripleQuotes.kt

fun main() {
  val s = "value"
  println("s = \"$s\".")
  println("""s = "$s".""")
}
/* 输出:
s = "value".
s = "value".
*/

使用三引号,你可以以与单引号 String 相同的方式插入表达式的值。

练习和解答可在 www.AtomicKotlin.com 找到。