Question

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()

Was it helpful?

Solution

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

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

Outputs,

zzzztest

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top