开发者

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开发者_如何学Go 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


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


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


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

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


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.


Yet another method is to use DecimalFormat:

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

String fourDigitString = df.format(numberFromDB);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜