Search code examples
javastringstring-formatting

String.format - Fill a String with dots


I have two Strings.

String a = "Abraham"
String b = "Best Friend"

I want an output similar to this:

Abraham.......OK
Best Friend...OK

I used String.format() to get the following result.

a = String.format("%0$-" + b.lenght() + "s   ", a);
b = String.format("%0$-" + b.lenght() + "s   ", b);

Abraham       OK
Best Friend   OK

I can not use String.replace(), because the space between "Best" and "Friend" would be replaced as well.

I found a solution for putting zeroes in front of the beginning of the String. However, i dont understand in which way I should modify this solution to get the desired output.

answer by anubhava

String sendID = "AABB";
String output = String.format("%0"+(32-sendID.length())+"d%s", 0, sendID);

I found solutions with padded Strings, but i would like to solve this with the String.format()-Method.


Solution

  • I'd probably use a loop for that (along with a StringBuilder for performance reasons:

    public String pad(String source, int targetLength, String pad) {
      StringBuilder result = new StringBuilder( source );
      for( int i = source.length(); i < targetLength; i+=pad.length() ) {
        result.append(pad);
      }
      return result.toString();
    }
    
    //calling:
    a = pad( a, 32, "." );
    

    Note that this would stop early if targetLength - source.length() is not a multiple of pad.length(). To fix that either only pass single characters or handle the last part by using pad.substring(...) with appropriate values.

    Edit:

    Here's a version with pad.subString(...):

    public String pad(String source, int targetLength, String pad) {
      StringBuilder result = new StringBuilder( source );    
      while( result.length() < targetLength ) {
        result.append(pad.substring( 0, Math.min( pad.length(), targetLength -  result.length() ) ));
      }
      return result.toString();
    }