4

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.

Ted Hopp
  • 222,293
  • 47
  • 371
  • 489
BRampersad
  • 832
  • 12
  • 25

4 Answers4

16

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));
Ted Hopp
  • 222,293
  • 47
  • 371
  • 489
5
org.apache.commons.lang.StringUtils.leftPad(String str, int size, char padChar)

You can take a look here

Piyush Mattoo
  • 14,524
  • 6
  • 49
  • 58
2

How about this:

s = (s.length()) < 8 ? ("00000000".substring(s.length()) + s) : s;

or

s = "00000000".substring(Math.min(8, s.length())) + s;

I prefer using an existing library method though, such as a method from Apache Commons StringUtils, or String.format(...). The intent of your code is clearer if you use a library method, assuming it is has a sensible name.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
1

The lazy way is to use something like: Right("00000000" + yourstring, 8) with simple implementations of the Right function available here: http://geekswithblogs.net/congsuco/archive/2005/07/07/45607.aspx

iivel
  • 2,546
  • 21
  • 19