如何在Scala中使用字符串插值格式化字符串作为固定宽度字符串?

myy*_*yyk 10 scala padding string-interpolation format-string scala-2.10

我正在与一个非常古老的系统连接,我需要生成的文件需要一个由字符串组成的字段,但需要正好是15个宽度.

我想要这样的东西:

val companyName = "FooBar, Inc" // 11 chars
f"$companyName%s"
Run Code Online (Sandbox Code Playgroud)

回来:

"    FooBar, Inc"
Run Code Online (Sandbox Code Playgroud)

是否有一种灵巧的方式来做我正在尝试使用字符串插值?

Ron*_*ren 15

String.format格式字符串一起使用.肯定会有你想要的东西:-)

这段代码可以满足您的需求:

scala> val companyName = "FooBar, Inc"
companyName: String = FooBar, Inc

scala> f"$companyName%15s"
res0: String = "    FooBar, Inc"
Run Code Online (Sandbox Code Playgroud)

  • 是的,预先挂起' - '到宽度说明符:`scala> f"$ companyName%-15s"` (3认同)
  • 我可以将 15 设为参数吗:例如 `val w=15`,现在执行以下操作:`f"$companyName%${w}s"` (2认同)
  • @drjerry - 尝试`companyName.formatted(s"%$ {w} s")`. (2认同)