Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 975
leif_good Avatar asked Mar 16 '26 18:03

leif_good


1 Answers

You can use replaceAll() with a regex like this:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String arr[] = {"Abraham", "Best Friend"};
        for(String s:arr)
            System.out.println(String.format("%-"+32+"s", s).replaceAll("\\s(?=\\s+$|$)", ".")+"OK");
    }
}

Output:

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

http://ideone.com/Rb886w

like image 178
riteshtch Avatar answered Mar 18 '26 07:03

riteshtch