0

How to add 5 pluses to an existing string using String.format?

I know that this way you can add spaces to an existing line:

String str = "Hello";
String padded = String.format("%-10s", str);

How to add plus? I did not find how the plus symbol is indicated.

the result should be:

"Hello+++++"
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kirill Sereda
  • 469
  • 1
  • 10
  • 25

4 Answers4

3

There is no flag that allows you to pad + instead of space. Instead you need to do something like:

String.format("%s%s", str, "+".repeat(5))

or maybe just:

str + ("+".repeat(5))

String.repeat was introduced in Java 11.

You could also just hardcode it:

String.format("%s+++++", str)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Thank you! The solution with "+".repeat(5) is very cool. Is there such a thing for Java 8? – Kirill Sereda May 05 '20 at 11:40
  • @KirillSereda Not in Java itself, but you could just Apache commons-lang3 which has [`org.apache.commons.lang3.StringUtils.repeat(String,int)`](http://commons.apache.org/proper/commons-lang/javadocs/api-3.10/org/apache/commons/lang3/StringUtils.html#repeat-java.lang.String-int-), or you could write a static helper method yourself. The linked duplicate also provides more alternative solutions. – Mark Rotteveel May 05 '20 at 11:44
  • Thank you so much! My solution: StringUtils.rightPad(str, 20, "+") – Kirill Sereda May 05 '20 at 11:51
1
String str = "Hello";
String padded = String.format("%s+++++", str);
System.out.println(padded);

? if you want to have it more generic and extract it to the method you can try to do sth like this:

String str = "Hello";
int size = 10;
String pluses = "";
for (int i = 0; i < size; i++) pluses = String.format("%s+", pluses);
String padded = String.format("%s%s", str, pluses);
System.out.println(padded);
Marcin Erbel
  • 1,597
  • 6
  • 32
  • 51
  • Thank you. But if there are 20 pluses? Is there any universal solution to indicate the number of pluses as in the example above with spaces? e.g. String.format ("% - 10s", str); – Kirill Sereda May 05 '20 at 11:38
  • I've updated my answer. If it's ok for you you can vote on + – Marcin Erbel May 05 '20 at 11:42
1
String str = "Hello"

String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";
RobCo
  • 6,240
  • 2
  • 19
  • 26
  • Thank you. But if there are 20 pluses? Is there any universal solution to indicate the number of pluses as in the example above with spaces? e.g. String.format ("% - 10s", str); – Kirill Sereda May 05 '20 at 11:38
1

String.format("%s%s", str, "++++");

This should work.

Mr. Nielzom
  • 317
  • 1
  • 2
  • 11
  • Thank you. But if there are 20 pluses? Is there any universal solution to indicate the number of pluses as in the example above with spaces? e.g. String.format ("% - 10s", str); – Kirill Sereda May 05 '20 at 11:39