Java String.format-用点填充字符串

Java String.format-用点填充字符串,java,string,string-formatting,Java,String,String Formatting,我有两条线 String a = "Abraham" String b = "Best Friend" 我想要类似于以下内容的输出: Abraham.......OK Best Friend...OK 我使用String.format()得到以下结果 a = String.format("%0$-" + b.lenght() + "s ", a); b = String.format("%0$-" + b.lenght() + "s ", b); Abraham OK

我有两条线

String a = "Abraham"
String b = "Best Friend"
我想要类似于以下内容的输出:

Abraham.......OK
Best Friend...OK
我使用String.format()得到以下结果

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

Abraham       OK
Best Friend   OK
我不能使用String.replace(),因为“Best”和“Friend”之间的空格也将被替换

我找到了一个解决方案,可以在字符串的开头放零。但是,我不知道应该以何种方式修改此解决方案以获得所需的输出


我找到了填充字符串的解决方案,但我想用String.format()-方法解决这个问题。

出于性能原因,我可能会使用一个循环(以及
StringBuilder

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, "." );
只是一个想法

public class Test {
  public static void main(String[] args) {
    String TEN_DOTS = "..........";
    String TEST_STR = "foo";
    String outstr = TEST_STR + TEN_DOTS;
    System.out.println(outstr.substring(0,10));
  }
}
产出:

foo.......

您可以将
replaceAll()
与如下正则表达式一起使用:

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");
    }
}
输出:

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

一种简单的递归方法是:

public static String fill(String s, int l){
    if(s.length()==l)
        return s; // Return the String , as the task is complete
    else 
        return fill(s+".",l); // Append 1 .(dot) and again call the method
}
a = fill(a,b.length());
b = fill(b,b.length());
这是我能想到的最简单的方法

因此,对你来说,这将是:

public static String fill(String s, int l){
    if(s.length()==l)
        return s; // Return the String , as the task is complete
    else 
        return fill(s+".",l); // Append 1 .(dot) and again call the method
}
a = fill(a,b.length());
b = fill(b,b.length());

可能是这样的:我不会在这里使用
String.format()
,而是使用
StringBuilder
并在循环中添加点。使用StringBuilder的解决方案似乎非常适合我的用例。在我的用例中,pad应该始终是一个字符,因此我决定将其设置为一个字符,然后“转换”(连接)如果不需要“cast”,则
StringBuilder
有一个
append(char)
方法。就像边节点一样:如果
l
很大,并且初始字符串很短,这可能会导致严重的内存问题,因为每个递归将创建至少一个中间字符串。因此,我建议在内部使用
StringBuilder
,即用于实际的递归调用。