Sunil Shahi
Sunil Shahi

Reputation: 653

Using java.lang.String.format() to pad a string with given character

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

Answers (2)

kiruwka
kiruwka

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

Jayamohan
Jayamohan

Reputation: 12924

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

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

Outputs,

zzzztest

Upvotes: 2

Related Questions