本文介绍了如何在Scala中使用字符串插值将字符串格式化为固定宽度的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在连接一个非常老的系统,我需要生成的文件需要一个由字符串组成的字段,但宽度必须恰好为15.
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.
我想要这样的东西:
val companyName = "FooBar, Inc" // 11 chars
f"$companyName%s"
要返回:
" FooBar, Inc"
是否有一种巧妙的方法可以完成我对String插值的处理?
Is there a slick way to do what I'm trying to do with the String interpolation?
推荐答案
使用和.当然有什么可以做你想要的:-)
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"
这篇关于如何在Scala中使用字符串插值将字符串格式化为固定宽度的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!