How to format a string n number of times with a specified character, and then append it to another string?

106 views Asked by At

As the title says, given a string, I would like to pad it (append) with n number of x character. Please see the below code. Is it possible to do that all in one String.format?

The commented line shows how to append n number of spaces; I would like to do the exact same thing with a custom character.

int paddingLength = (int) args.get(0); 
String paddingItem = (String) args.get(1); 

String temp = ((String) row.get(fieldName));


//temp = String.format("%-" + n + "s", s); 

temp = String.format("%-" + paddingLength + "paddingItem", paddingItem + "temp", temp); 

Example:

paddingLength: 5
paddingItem: "_"
temp = "test"

result: "test_____"
1

There are 1 answers

0
Dylanrr On

Another option is using StringBuilder. Example.

int n = 5;
char x = '_';
String temp = "test";
StringBuilder paddedWord = new StringBuilder(temp);
for(int i=0; i<n; i++)
    paddedWord.append(x);

Just remember to cast your StringBuilder back to a String if you are using it elsewhere .toString()