Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad digits until string is 8 chars long in java?

i was reading and couldn't find quite the snippet. I am looking for a function that takes in a string and left pads zeros (0) until the entire string is 8 digits long. All the other snippets i find only lets the integer control how much to pad and not how much to pad until the entire string is x digits long. in java.

Example

BC238 => 000BC289
4 => 00000004

etc thanks.

like image 366
BRampersad Avatar asked Nov 28 '22 10:11

BRampersad


1 Answers

If you're starting with a string that you know is <= 8 characters long, you can do something like this:

s = "00000000".substring(0, 8 - s.length()) + s;

Actually, this works as well:

s = "00000000".substring(s.length()) + s;

If you're not sure that s is at most 8 characters long, you need to test it before using either of the above (or use Math.min(8, s.length()) or be prepared to catch an IndexOutOfBoundsException).

If you're starting with an integer and want to convert it to hex with padding, you can do this:

String s = String.format("%08x", Integer.valueOf(val));
like image 148
Ted Hopp Avatar answered Dec 05 '22 17:12

Ted Hopp