增量后将整数零填充为字符串

时间:2015-04-09 07:48:03

标签: java

我需要增加一个只有数字的字符串:

String current = "000433"; //After increment, will be "000434"

我有这个程序,它正常工作:

private String incrementOne(String numberAsString) {
    int leftZeroCount = countLeadingZeros(numberAsString);
    Integer asInteger = Integer.parseInt(numberAsString);
    asInteger++;
    return parseStringWithNZeros(asInteger, leftZeroCount);
}

private String parseStringWithNZeros(Integer asInteger, int leftZeroCount) {
    String asString = Integer.toString(asInteger);
    for (int i = 0; i < leftZeroCount; i++)
        asString = "0" + asString;
    return asString;
}

private int countLeadingZeros(String numberAsString) {
    int count = 0;
    int i = 0;
    while (numberAsString.charAt(i) == '0' && i < numberAsString.length()) {
        count++;
        i++;
    }
    return count;
}

过程是:

  1. 计算左边的零
  2. Parse to Integer
  3. 增加一个
  4. Parse to String
  5. 添加左边的零
  6. String的数字长度未知。我确信存在另一种更容易和更清洁的方式,使用正则表达式或其他东西。我可以采用哪些替代方案?

    感谢。

2 个答案:

答案 0 :(得分:14)

如何使用String.format()

这样做
String original = "000433";
String incremented = String.format("%0" + original.length() + "d",
            Integer.parseInt(original) + 1);

System.out.println(incremented);

答案 1 :(得分:0)

试试这个:

private String incrementOne(String numberAsString) {
   int length = numberAsString.length();
   Integer asInteger = Integer.parseInt(numberAsString);
   asInteger++;
   numberAsString = asInteger.toString();
   while(numberAsString.length() < length){
      numberAsString = "0" + numberAsString;
      count ++;
   }
   return numberAsString;
}