Your instincts are good here, in almost all respects. Your basic algorithm is good, and your suspicions that you are changing too often between String an charString and char is also good.
Using the StringBuilderStringBuilder is the right thing to do,do; well done. Breaking the String in toString into chars is also good, but the way you do that is inconvenient.... In part that's because there is a convenient function in the standard Java Character class that you will find useful: Character.isDigit(char)
The code still assumes valid input (where the last character cannot be a digit, or it is lost). Additionally, I tweaked it to handle multiple digit input.... like 20z"20z" ... for fun.
You should never use exception handling (trytry/catchcatch) to handle normal program flow. The try/parse/catch logic you have is very slow to run. Throwing an exception for every non-digit character will be a lot of overhead. Even though Java has improved in terms of performance, when processing exceptions, it is still much slower than the alternatives, like a regular expression, or some other mechanism...
- Use the 'repeat'Uses
repeatas a flag set to negative for nothing. This allows for input likeab01which will outputab1(which would be impossible without the 0-repeat option). - Note that the repeat is now also used as a flag for the isDigit
isDigitcheck. - a do
do-whilewhileloop instead of a whilewhile-dodoloop (as per Josay's comment).