Friday, 24 January 2020

Java: Left pad a string with zeros


Following snippet left pad given string with zeros.
String.format("%" + n + "s", str).replace(' ', '0');

App.java
package com.sample.app;

public class App {

 private static String leftPad(String str, int n) {
  return String.format("%" + n + "s", str).replace(' ', '0');
 }

 public static void main(String[] args) {
  String paddedString = leftPad("hello", 16);

  System.out.println(paddedString);

 }

}

Output
00000000000hello



You may like

No comments:

Post a Comment