Reputation: 653
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()
Upvotes: 1
Views: 2915
Reputation: 9450
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;
Upvotes: 0