1

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

0

2 Answers 2

2

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

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

Outputs,

zzzztest

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.