使用格式化程序用 0 填充字符串
我知道我可以使用 : 填充空格,
String.format("%6s", "abc"); // ___abc ( three spaces before abc
但我似乎找不到如何生成:
000abc
编辑:
在询问此问题之前我尝试过 %06s
。只是在更多(未经尝试的)答案出现之前让您知道。
目前我有: String.format("%6s", data ).replace(' ', '0' )
但我认为必须存在更好的方法。
I know I can fill with spaces using :
String.format("%6s", "abc"); // ___abc ( three spaces before abc
But I can't seem to find how to produce:
000abc
Edit:
I tried %06s
prior to asking this. Just letting you know before more ( untried ) answers show up.
Currently I have: String.format("%6s", data ).replace(' ', '0' )
But I think there must exists a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您确实应该考虑使用 StringUtils 用于此类字符串操作任务,因为您的代码将变得更具可读性。您的示例为
StringUtils.leftPad("abc", 6, ' ');
You should really consider using StringUtils from Apache Commons Lang for such String manipulation tasks as your code will get much more readable. Your example would be
StringUtils.leftPad("abc", 6, ' ');
尝试滚动您自己的静态实用程序方法
,然后使用它,例如
OUTPUT
Try rolling your own static-utility method
And then use it, as such
OUTPUT
无论如何,找到一个你喜欢的此类东西的库,并了解你闪亮的新工具箱中有什么,这样你就可以重新发明更少的轮子(有时有扁平的)。我更喜欢 Guava 到 Apache Commons。在这种情况下它们是等效的:
By all means, find a library you like for this kind of stuff and learn what's in your shiny new toolbox so you reinvent fewer wheels (that sometimes have flats). I prefer Guava to Apache Commons. In this case they are equivalent:
快速而肮脏(将“000....00”字符串的长度设置为您支持的最大长度):
Quick and dirty (set the length of the "000....00" string as the maximum len you support) :
我认为这就是您正在寻找的。
I think this is what you're looking for.