How to make a String.format flag with a variable inside [closed]

Tags: ,



I need to format a numeric String to be of length k, which is the length of a parameter String. How do I get String.format() to use a flag like "%0kd"?

Edit: I realise String.format() does not support what I need. A better question is how to get it.

Answer

You can do it this way:

int k = 5;
System.out.println(String.format("%0" + k + "d", 10));

It prints:

00010



Source: stackoverflow