Java 中递增计数器并显示为零填充字符串
是否有任何现有实用程序(例如 Apache Commons StringUtils)可以轻松递增整数,但将其输出为零填充字符串?
我当然可以利用诸如 String.format("%05d", counter) 之类的东西编写自己的代码,但我想知道是否有一个库已经提供了这个功能。
我正在设想可以这样使用的东西:
// Create int counter with value of 0 padded to 4 digits
PaddedInt counter = new PaddedInt(0,4);
counter.incr();
// Print "0001"
System.out.println(counter);
// Print "0002"
System.out.println(counter.incr());
String text = "The counter is now "+counter.decr();
// Print "The counter is now 0001"
System.out.println(text);
Are there any existing utilities like Apache Commons StringUtils that make it easy to increment an integer, but output it as a zero padded string?
I can certainly write my own utilizing something like String.format("%05d", counter)
, but I'm wondering if there is a library that has this already available.
I'm envisioning something I can use like this:
// Create int counter with value of 0 padded to 4 digits
PaddedInt counter = new PaddedInt(0,4);
counter.incr();
// Print "0001"
System.out.println(counter);
// Print "0002"
System.out.println(counter.incr());
String text = "The counter is now "+counter.decr();
// Print "The counter is now 0001"
System.out.println(text);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑您会找到任何方法来执行此操作,因为填充和递增是两个不相关的基本操作,并且实现起来很简单。在你写问题的时间内,你可以实施这样的课程三次。这一切都归结为将 int 包装到对象中并使用
String.format
实现 toString。I doubt you'll find anything to do this, because padding and incrementing are two basic operations that are unrelated, and trivial to implement. You could have implemented such a class three times in the time you took to write your question. It all boils down to wrapping an int into an object and implementing toString using
String.format
.如果有人感兴趣,我在发布问题几分钟后将其放在一起:
唯一的问题是我必须调用 toString() 来从中获取字符串,或将其附加到类似
""+counter
的字符串:In case anyone is interested, I threw together this a few minutes after posting my question:
The only problem with this is that I must call
toString()
to get a string out of it, or append it to a string like""+counter
:老实说,我认为你混合了不同的担忧。整数是具有所有操作的整数,如果你想输出它用零填充,那就是不同的事情了。
您可能想看看
StringUtils.leftPad
作为String.format
的替代。To be honest, I think you are mixing different concerns. An integer is an integer with all the operations and if you want to output it padded with zeros that is different thing.
You might want to have a look at
StringUtils.leftPad
as an alternative ofString.format
.