Search code examples
javastringstring-concatenationstring.format

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


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

Solution

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