Pad digits to string 8 characters in java?

I read and could not find a pretty fragment. I am looking for a function that takes a string and left zeros (0) until the entire string contains 8 digits. All the other fragments that I find allow only an integer to control the size, and not until the whole line contains x digits. in java.

Example

BC238 => 000BC289
4 => 00000004

etc. thanks.

+4
source share
4 answers

If you start with a line that you know is <= 8 characters long, you can do something like this:

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

Actually, this also works:

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

If you are not sure that s is no more than 8 characters long, you need to check it before using any of the above (or use Math.min(8, s.length()) or prepare to detect IndexOutOfBoundsException ).

If you start with an integer and want to convert it to hex with the addition, you can do this:

 String s = String.format("%08x", Integer.valueOf(val)); 
+16
source
 org.apache.commons.lang.StringUtils.leftPad(String str, int size, char padChar) 

You can look here

+5
source

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 to use an existing library method, for example, a method from Apache Commons StringUtils or String.format(...) . The purpose of your code is clearer if you use the library method, assuming it has a reasonable name.

+2
source

A sneaky 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

+1
source

Source: https://habr.com/ru/post/1345389/


All Articles