简体   繁体   中英

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

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_____"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM