3

I need to increment by one an String that is only digits:

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

I have this procedure, that works properly:

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;
}

The process is:

  1. Count the left zeros
  2. Parse to Integer
  3. Increment by one
  4. Parse to String
  5. Add the left zeros

The length of the number as String is unknown. I am sure that exists another easier and cleaner way, with regex or something. Which alternatives can I adopt?

Thanks.

Antxon
  • 1,855
  • 15
  • 21
Héctor
  • 24,444
  • 35
  • 132
  • 243
  • 2
    This might be a better fit for http://codereview.stackexchange.com/ – reto Apr 09 '15 at 07:51
  • 2
    Nothing wrong with that solution, except I guess you expect the next value for 000999 to be 001000 and not 0001000. Your method parse doesn't parse, it formats. So its name should be formatWithNZeros. – JB Nizet Apr 09 '15 at 07:54
  • Check the post http://stackoverflow.com/questions/275711/add-leading-zeroes-to-number-in-java – HJK Apr 09 '15 at 07:54
  • @user3694267 - or the original : http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left – Gnoupi Apr 09 '15 at 07:56
  • Thanks! @JBNizet you're right. Actually, my code is not contemplating this case. Next value for 000999 would be 0001000 in my code, but it is wrong. – Héctor Apr 09 '15 at 08:44
  • I'm voting to close this question as off-topic because it belongs on codereview.stackexchange.com – Colin 't Hart Apr 09 '15 at 09:08

2 Answers2

19

How about doing it like this, using String.format():

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

System.out.println(incremented);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

Try this:

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;
}
Blip
  • 3,061
  • 5
  • 22
  • 50