public class LeadingZerosExample {
public static void main(String[] args) {
int number = 1500;
// String format below will add leading zeros (the %0 syntax)
// to the number above.
// The length of the formatted string will be 7 characters.
String formatted = String.format("%07d", number);
System.out.println("Number with leading zeros: " + formatted);
}
}
public class Test {
public static void main(String[] args){
System.out.println(padCharacter("0",8,"hello"));
}
public static String padCharacter(String c, int num, String str){
for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
return str;
}
}
public static String prefixZeros(String value, int len) {
char[] t = new char[len];
int l = value.length();
int k = len-l;
for(int i=0;i<k;i++) { t[i]='0'; }
value.getChars(0, l, t, k);
return new String(t);
}
//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros.
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string.
String.format("%1$10s", "mystring" ).replace(" ","0");
public static String addLeadingText(int length, String pad, String value) {
String text = value;
for (int x = 0; x < length - value.length(); x++) text = pad + text;
return text;
}
你可以使用上面的方法addLeadingText(length, padding text, your text)