-1

I am trying to make a program that given a string such as "hi99" it'd return "hi100", so basically adding 1 to the numbers in the last spots.

public static String incrementString(String str) {
        String nonNumber = "";
        String number = "";
        int numberInt = 0;
        for(int i = str.length() - 1 ; i >= 0 && Character.isDigit(str.charAt(i)); i--){
            nonNumber = str.substring(0, i);
            number  = str.substring(i);     
        }   
        numberInt = Integer.valueOf(number) + 1;
        number = Integer.toString(numberInt);
        return (nonNumber + number);
    }

My idea was to split the part with numbers from the part with no numbers. And then add one to the numbered part. Which is what i do below. Problem comes with the fact that, when Java sees 001, instead of adding 1 to the last spot and ignoring the rest. The ending value is 2. Therefore, I'm just asking to see if there's a way to avoid the removal of those zeroes.

Koma
  • 1
  • 1

1 Answers1

0

Had a similar assignment a few years back. Try this!

public String inc_string(String src){
    int c = 0;
    boolean inc_left = false;

    StringBuilder sb = new StringBuilder(src);
    for (c = sb.length() - 1; c > 0; c--){
        char tc = sb.charAt(c);
        if (!Character.isDigit(tc) && inc_left){
            sb.insert(c + 1, '1');
            return sb.toString();
        }
        if (Character.isDigit(tc)){
            inc_left = false;
            if (tc >= '9'){
                tc = '0';
                inc_left = true;
            }
            else{
                tc++;
            }
            sb.setCharAt(c, tc);
            if (!inc_left){
                return sb.toString();
            }
        }
    }
    return src;
}
BitWiseByteDumb
  • 159
  • 1
  • 12