If you want to pad the string to the specified number of digits, use the ** "String.format" ** method.
String.format
padding.java
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
String result5keta = blankPadding5keta();
String result10keta = blankPadding10keta();
System.out.println(result5keta);
System.out.println(result10keta);
}
//Fill with 5 digits
private static String blankPadding5keta(){
String str = "123";
String paddingStr = str.format("%5s", str);
return paddingStr;
}
//Fill in blanks with 10 digits
private static String blankPadding10keta(){
String str = "12345";
String paddingStr = str.format("%10s", str);
return paddingStr;
}
}
result
12345
12345
padding.java
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
String result5keta = zeroPadding5keta();
String result10keta = zeroPadding10keta();
System.out.println(result5keta);
System.out.println(result10keta);
}
//Fill with 0 in 5 digits
private static String zeroPadding5keta(){
String str = "123";
String paddingStr = str.format("%5s", str).replace(" ", "0");
return paddingStr;
}
//Fill with 0 in 10 digits
private static String zeroPadding10keta(){
String str = "12345";
String paddingStr = str.format("%10s", str).replace(" ", "0");
return paddingStr;
}
}
result
00123
0000012345
Recommended Posts