How do I format a string with string interpolation in Scala as a fixed width string?

匆匆过客 提交于 2020-01-11 01:26:51

问题


I'm interfacing with a really old system and the file I need to generate needs a field that is a formed from a string but needs to be exactly 15 in width.

I want something like this:

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

To return:

"    FooBar, Inc"

Is there a slick way to do what I'm trying to do with the String interpolation?


回答1:


Use String.format with a format string. Surely something there will do what you want :-)

This code would do what you want:

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

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


来源:https://stackoverflow.com/questions/15375231/how-do-i-format-a-string-with-string-interpolation-in-scala-as-a-fixed-width-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!