0

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_____"
dk40149
  • 99
  • 1
  • 10
  • https://stackoverflow.com/questions/3450758/string-format-to-fill-a-string – kai Feb 06 '19 at 21:09
  • Possible duplicate of [Simple way to repeat a String in java](https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string-in-java) – uneq95 Feb 06 '19 at 21:11
  • @kai Hi, thanks for the response. Unfortunately that has to do with replacing characters - I want to append characters where there were no characters before. – dk40149 Feb 06 '19 at 21:12
  • @uneq95 Not to do with replacing characters. Please see the example I just edited with – dk40149 Feb 06 '19 at 21:14
  • 1
    you want instead the of the space in the example underscores -> replace the spaces with underscores. – kai Feb 06 '19 at 21:20
  • What is args here? Whatever it is, are you sure you can cast one member to an int and another to a String? – FredK Feb 06 '19 at 21:22
  • 1
    String.format("%-" + n + "s", s).replace(' ','_'); – kai Feb 06 '19 at 21:23
  • Use `paddingItem.repeat(paddingLength)` *(Java 11+)* – Andreas Feb 06 '19 at 21:26
  • When you set the padding length as 5, then for the string "test", it will append only 1 space character, not 5, to the end of "test". – uneq95 Feb 06 '19 at 21:29

1 Answers1

1

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

Dylanrr
  • 31
  • 1
  • 6