【问题标题】:How do I format a string with string interpolation in Scala as a fixed width string?如何在Scala中将带有字符串插值的字符串格式化为固定宽度的字符串?
【发布时间】:2013-02-28 19:01:26
【问题描述】:

我正在与一个非常旧的系统交互,我需要生成的文件需要一个由字符串组成的字段,但宽度必须正好为 15。

我想要这样的东西:

val companyName = "FooBar, Inc" // 11 chars
f"$companyName%s"

返回:

"    FooBar, Inc"

有没有一种巧妙的方法来做我想要用字符串插值做的事情?

【问题讨论】:

  • 这个问题现在看起来很简单,这是因为当我一直有解决方案时我做错了其他事情,所以我把这个问题删掉了,所以它是有道理的。

标签: scala padding scala-2.10 string-interpolation format-string


【解决方案1】:

String.formatformat string 一起使用。当然,那里的东西会做你想做的:-)

这段代码会做你想做的事:

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

scala> f"$companyName%15s"
res0: String = "    FooBar, Inc"

【讨论】:

  • 哦,哇。我要编辑我的问题,因为它甚至不正确。我不知道我在 REPL 中输入了什么,因为这确实有效。谢谢。
  • 这种方法是否可以获得左对齐格式(右侧填充空格)?
  • 是的,在宽度说明符前加上“-”:scala> f"$companyName%-15s"
  • 我可以将 15 设为一个参数吗:像 val w=15 现在执行类似的操作:f"$companyName%${w}s"
  • @drjerry 可能实现此类目标的唯一方法是使用String.format("%" + w + "s", w, companyName)
猜你喜欢
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 2018-01-28
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多