Java pad string with specific characters

Viewed 295

I have a string apple I want it maximum 8 character long.

So i have apple. its 5 chars long. I pad it with 3* to make it ***apple

So i have bat. its 3 chars long. I pad it with 5* to make it *****bat

Is there any way to do it? Cant find any padding library out there.

4 Answers

Other way how you can do it:

String.format("%8s", "helllo").replace(' ', '*');

In this case you do not need to add library.

tl;dr

Built into Java 11+

"*"                             // A single-character string.
.repeat( 8 - "apple".length )   // `String::repeat` multiplies text. Here we return a `String` of a certain number of asterisks.
.concat( "apple" ) ;            // Appends to those asterisks our original input. 

***apple

String::repeat

Java 11 brought a new method, repeat, to the String class. This method multiplies a piece of text a certain number of times. Multiplying by zero is valid, resulting in an empty string.

In our case, we want to multiply a single character string, *.

int goal = 8 ; 
String input = "apple" ;
int length = input.length() ;
String output = "*".repeat( goal - length ).concat( input ) ;

See this code run live at IdeOne.com.

***apple

You can use StringUtils.leftPad from Apache Commons Lang library

StringUtils.leftPad(null, *, *)     = null
StringUtils.leftPad("", 3, 'z')     = "zzz"
StringUtils.leftPad("bat", 3, 'z')  = "bat"
StringUtils.leftPad("bat", 5, 'z')  = "zzbat"
StringUtils.leftPad("bat", 1, 'z')  = "bat"
StringUtils.leftPad("bat", -1, 'z') = "bat"

No library needed. Uses a StringBuilder and reverse() for speed (insert is slower than append):

public String padWord(String word)
{
    if(word.length() < 8)
    {
        StringBuilder foo = new StringBuilder(word);
        foo = foo.reverse();
        for(int x = word.length(); x < 8; x++)
        {
            foo.append('*');
        }
        foo.reverse();
    }
    return foo.toString();
}
Related