Take the 2-minute tour ×

I have a string and I want to pad this string by any given character to a given length. off course I can write a loop statement and get the job done but thats not what I am looking for.

One approach I used was

myString = String.format("%1$"+ n + "s", myString).replace(' ', newChar);

this works fine except when myString already has a space in it. Is there a better solution using String.format()

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can try using Commons StringUtils rightPad or leftPad method, like below.

StringUtils.leftPad("test", 8, 'z');



share|improve this answer

If your string does not contain '0' symbols, you could do :

 int n = 30; // assert that n > test.length()
 char newChar = 'Z';
 String test = "string with no zeroes";
 String result = String.format("%0" + (n - test.length()) + "d%s", 0, test)
     .replace('0', newChar); 
 // ZZZZZZZZZstring with no zeroes

or if it does :

 test = "string with 0 00";
 result = String.format("%0" + (n - test.length()) + "d", 0).replace('0', newChar)
     + test;
 // ZZZZZZZZZZZZZZstring with 0 00

 // or equivalently:
 result = String.format("%" + (n - test.length()) + "s", ' ').replace(' ', newChar) 
     + test;
share|improve this answer

Your Answer


