填充数字,直到字符串是在java中8个字符长? [英] Pad digits until string is 8 chars long in java?

查看:450
本文介绍了填充数字,直到字符串是在java中8个字符长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读,无法找到相当的片段。我正在寻找一个函数,它接受一个字符串并将填充零(0),直到整个字符串的长度为8位数。我发现的所有其他片段只允许整数控件填充多少,而不是填充多少,直到整个字符串为x数字长为止。



示例


BC238 => 000BC289

4 => 00000004


等谢谢。

解决方案

如果您开始使用的字符串长度不超过8个字符,您可以这样做:

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

实际上,这也适用:

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

如果您不确定 s 最多8个字符长,您需要在使用上述任一项之前测试它(或使用 Math.min(8,s.length())或准备捕获一个 IndexOutOfBoundsException )。

如果你从一个整数开始并且想用padding将它转换为十六进制,你可以这样做:

  String s = String.format(%08x,Integer.valueOf(val)); 


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.

解决方案

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));

这篇关于填充数字,直到字符串是在java中8个字符长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆