0

是否有任何现有的实用程序,如 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);
4

3 回答 3

1

万一有人感兴趣,我在发布我的问题几分钟后把这个放在一起:

import org.apache.commons.lang.StringUtils;

public class Counter {

    private int value;
    private int padding;

    public Counter() {
        this(0, 4);
    }

    public Counter(int value) {
        this(value, 4);
    }

    public Counter(int value, int padding) {
        this.value = value;
        this.padding = padding;
    }

    public Counter incr() {
        this.value++;
        return this;
    }

    public Counter decr() {
        this.value--;
        return this;
    }

    @Override
    public String toString() {
        return StringUtils.leftPad(Integer.toString(this.value), 
                this.padding, "0");
        // OR without StringUtils:
        // return String.format("%0"+this.padding+"d", this.value);
    }
}

唯一的问题是我必须调用toString()以从中获取字符串,或将其附加到如下字符串""+counter

@Test
public void testCounter() {
    Counter counter = new Counter();
    assertThat("0000", is(counter.toString()));
    counter.incr();
    assertThat("0001",is(""+counter));
    assertThat("0002",is(counter.incr().toString()));
    assertThat("0001",is(""+counter.decr()));
    assertThat("001",is(not(counter.toString())));
}
于 2011-11-19T08:56:34.567 回答
1

我怀疑您会找到任何方法来执行此操作,因为填充和递增是两个不相关且易于实现的基本操作。在你写问题的时间里,你可能已经实现了 3 次这样的类。这一切都归结为将一个 int 包装到一个对象中并使用 toString 实现String.format

于 2011-11-18T22:15:52.523 回答
0

老实说,我认为您正在混合不同的关注点。整数是一个包含所有操作的整数,如果你想输出它用零填充,那就不同了。

您可能想看看StringUtils.leftPad作为String.format.

于 2011-11-18T22:17:57.490 回答