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

パディングとインクリメントは無関係な 2 つの基本的な操作であり、実装するのは簡単なので、これを行う方法が見つかるとは思えません。質問を書くのにかかった時間で、そのようなクラスを 3 回実装できたはずです。要するに、int をオブジェクトにラップし、toString を使用して実装することString.formatです。

于 2011-11-18T22:15:52.523 に答える
0

正直なところ、さまざまな懸念が混在していると思います。整数はすべての操作を含む整数であり、出力したい場合はゼロで埋められますが、これは別のことです。

StringUtils.leftPadの代わりに をご覧になることをお勧めしますString.format

于 2011-11-18T22:17:57.490 に答える