Pad digits until string is 8 chars long in java?

主宰稳场 提交于 2019-12-05 14:03:41

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));
org.apache.commons.lang.StringUtils.leftPad(String str, int size, char padChar)

You can take a look here

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!