En este tutorial veremos cómo rellenar a la derecha una cadena con espacios y ceros:
1) Almohadilla derecha con espacios
public class PadRightExample1 { public static void main(String[] argv) { System.out.println("https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/#" + rightPadding("mystring", 10) + "@"); System.out.println("https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/#" + rightPadding("mystring", 15) + "@"); System.out.println("https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/#" + rightPadding("mystring", 20) + "@"); } public static String rightPadding(String str, int num) { return String.format("%1$-" + num + "s", str); } }
Producción:
#mystring @ #mystring @ #mystring @
2) Pad derecho con ceros
public class PadRightExample2 { public static void main(String[] argv) { System.out.println("https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/#" + rightPadZeros("mystring", 10) + "@"); System.out.println("https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/#" + rightPadZeros("mystring", 15) + "@"); System.out.println("https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/#" + rightPadZeros("mystring", 20) + "@"); } public static String rightPadZeros(String str, int num) { return String.format("%1$-" + num + "s", str).replace(' ', '0'); } }
Producción:
#[email protected] #[email protected] #[email protected]