headscratch
headscratch

Reputation: 551

Strings - Filling In Leading Zeros Wtih A Zero

I'm reading an array of hard-coded strings of numeric characters - all positions are filled with a character, even for the leading zeros. Thus, can confidently parse it using substring(start, end) to convert to numeric.

Example: "0123 0456 0789"

However, a string coming from a database does not fill in the leading zero with a 'zero character', it simply fetches the '123 456 789', which is correct for an arithmetic number but not for my needs and makes for parsing trouble.

Before writing conditionals to check for leading zeros and adding them to the string if needed, is there a simple way of specifying they be filled with a character ? I'm not finding this in my Java book...

I could have done the three conditionals in the time it took to post this but, this is more about 'education'...

Thanks

Upvotes: 2

Views: 1495

Answers (5)

jzd
jzd

Reputation: 23629

Yet another method is to use DecimalFormat:

DecimalFormat df = new DecimalFormat("####")'

String fourDigitString = df.format(numberFromDB);

Upvotes: 0

Claude
Claude

Reputation: 453

Perhaps StringUtils from org.apache.commons.lang could be useful for you:

StringUtils.leftPad("123", 4, '0') = "0123"

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81064

Simple regex way:

String input = "123 456 789";
String output = input.replaceAll("\\b[1-9]\\d*", "0$0");
System.out.println(output); //prints "0123 0456 0789"

This replaces all "words" consisting of any digit but beginning with 1-9 (not 0) with the same word, prefixed by 0.

I agree with the other assessments that you should just make your parsing less fragile, using something like String.split() instead of requiring fixed widths.

Upvotes: 0

Peter Taylor
Peter Taylor

Reputation: 5036

String.format("%010d", number); or fromDB.replaceAll(" ", "0"); or possibly even better, fix it in the DB.

Upvotes: 2

Anon.
Anon.

Reputation: 59973

An easier way to do it would be to use string.split() to separate the numbers, instead of pulling out specific character indices.

Upvotes: 2

Related Questions