scala 的string.format 用法
时间: 2023-08-11 11:35:26 浏览: 58
在 Scala 中,可以使用 `format()` 方法来格式化字符串。该方法与 Java 中的 `String.format()` 方法类似。
以下是 `format()` 方法的基本用法:
```scala
val str = "Hello, %s!".format("Scala")
println(str) // 输出:Hello, Scala!
```
在上面的例子中,`%s` 是格式化字符串中的占位符,它将被后面的参数 `"Scala"` 替换。
除了 `%s` 之外,还有其他类型的占位符可以使用。以下是常见的占位符类型及其用法:
| 占位符 | 类型 | 示例 |
|--------|------------|--------------------------|
| `%s` | 字符串 | `"Hello, %s!".format("world")` → `"Hello, world!"` |
| `%d` | 整数 | `"I have %d apples".format(3)` → `"I have 3 apples"` |
| `%f` | 浮点数 | `"Pi is approximately %f".format(3.14159)` → `"Pi is approximately 3.141590"` |
| `%c` | 字符 | `"The first letter of the alphabet is %c".format('A')` → `"The first letter of the alphabet is A"` |
| `%b` | 布尔值 | `"It is %b that 1 + 1 = 3".format(false)` → `"It is false that 1 + 1 = 3"` |
| `%x` | 十六进制数 | `"The number 255 in hex is %x".format(255)` → `"The number 255 in hex is ff"` |
除了基本类型之外,还可以使用额外的占位符来指定更复杂的格式,如日期和时间等。例如:
```scala
import java.time.LocalDateTime
val now = LocalDateTime.now()
println("Current time: %tT".format(now)) // 输出:Current time: 16:20:30
```
这里的 `%tT` 是时间格式的占位符。有关更多占位符类型及其用法,请参阅 Scala 官方文档。