我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
当前回答
老问题了,但我也有两个方法。
对于固定(预定义的)长度:
public static String fill(String text) {
if (text.length() >= 10)
return text;
else
return "0000000000".substring(text.length()) + text;
}
对于可变长度:
public static String fill(String text, int size) {
StringBuilder builder = new StringBuilder(text);
while (builder.length() < size) {
builder.append('0');
}
return builder.toString();
}
其他回答
以下是我的解决方案:
String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);
输出:00000101
如果你需要性能并且知道字符串的最大大小,使用以下方法:
String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;
注意最大字符串大小。如果它大于StringBuffer的大小,你会得到一个java.lang.StringIndexOutOfBoundsException。
格式化字符串使用
import org.apache.commons.lang.StringUtils;
public class test {
public static void main(String[] args) {
String result = StringUtils.leftPad("wrwer", 10, "0");
System.out.println("The String : " + result);
}
}
输出:字符串:00000wrwer
其中第一个参数是要格式化的字符串,第二个参数是所需输出长度的长度,第三个参数是字符串要填充的字符。
使用链接下载罐子http://commons.apache.org/proper/commons-lang/download_lang.cgi
我更喜欢这样的代码:
public final class StrMgr {
public static String rightPad(String input, int length, String fill){
String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
return pad.substring(0, length);
}
public static String leftPad(String input, int length, String fill){
String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
return pad.substring(pad.length() - length, pad.length());
}
}
然后:
System.out.println(StrMgr.leftPad("hello", 20, "x"));
System.out.println(StrMgr.rightPad("hello", 20, "x"));
右填充固定长度-10: 字符串。格式(“% 1 $ -10年代”,“abc”) 左填充固定长度-10: 字符串。格式(“% 1 $ 10 s”、“abc”)