有一些简单的方法来填充字符串在Java?

似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。


当前回答

概括一下Eko的答案(Java 11+):

public class StringUtils {
    public static String padLeft(String s, char fill, int padSize) {
        if (padSize < 0) {
            var err = "padSize must be >= 0 (was " + padSize + ")";
            throw new java.lang.IllegalArgumentException(err);
        }

        int repeats = Math.max(0, padSize - s.length());
        return Character.toString(fill).repeat(repeats) + s;
    }

    public static String padRight(String s, char fill, int padSize) {
        if (padSize < 0) {
            var err = "padSize must be >= 0 (was " + padSize + ")";
            throw new java.lang.IllegalArgumentException(err);
        }

        int repeats = Math.max(0, padSize - s.length());
        return s + Character.toString(fill).repeat(repeats);
    }

    public static void main(String[] args) {
        System.out.println(padLeft("", 'x', 5)); // => xxxxx
        System.out.println(padLeft("1", 'x', 5)); // => xxxx1
        System.out.println(padLeft("12", 'x', 5)); // => xxx12
        System.out.println(padLeft("123", 'x', 5)); // => xx123
        System.out.println(padLeft("1234", 'x', 5)); // => x1234
        System.out.println(padLeft("12345", 'x', 5)); // => 12345
        System.out.println(padLeft("123456", 'x', 5)); // => 123456

        System.out.println(padRight("", 'x', 5)); // => xxxxx
        System.out.println(padRight("1", 'x', 5)); // => 1xxxx
        System.out.println(padRight("12", 'x', 5)); // => 12xxx
        System.out.println(padRight("123", 'x', 5)); // => 123xx
        System.out.println(padRight("1234", 'x', 5)); // => 1234x
        System.out.println(padRight("12345", 'x', 5)); // => 12345
        System.out.println(padRight("123456", 'x', 5)); // => 123456

        System.out.println(padRight("1", 'x', -1)); // => throws
    }
}

其他回答

看看org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)。

但算法非常简单(填充到字符大小):

public String pad(String str, int size, char padChar)
{
  StringBuilder padded = new StringBuilder(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}

@ck和@Marlon Tarak的答案是唯一使用char[]的答案,对于每秒有几个填充方法调用的应用程序来说,这是最好的方法。然而,它们没有利用任何数组操作优化,而且对我来说有点覆盖;这完全不需要循环。

public static String pad(String source, char fill, int length, boolean right){
    if(source.length() > length) return source;
    char[] out = new char[length];
    if(right){
        System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
        Arrays.fill(out, source.length(), length, fill);
    }else{
        int sourceOffset = length - source.length();
        System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
        Arrays.fill(out, 0, sourceOffset, fill);
    }
    return new String(out);
}

简单测试方法:

public static void main(String... args){
    System.out.println("012345678901234567890123456789");
    System.out.println(pad("cats", ' ', 30, true));
    System.out.println(pad("cats", ' ', 30, false));
    System.out.println(pad("cats", ' ', 20, false));
    System.out.println(pad("cats", '$', 30, true));
    System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}

输出:

012345678901234567890123456789
cats                          
                          cats
                cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy 

使用该函数。

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

如何使用?

leftPadding(month, 2, '0');

输出: 01 02 03 04 ..11日12

public static String padLeft(String in, int size, char padChar) {                
    if (in.length() <= size) {
        char[] temp = new char[size];
        /* Llenado Array con el padChar*/
        for(int i =0;i<size;i++){
            temp[i]= padChar;
        }
        int posIniTemp = size-in.length();
        for(int i=0;i<in.length();i++){
            temp[posIniTemp]=in.charAt(i);
            posIniTemp++;
        }            
        return new String(temp);
    }
    return "";
}

你可以通过保留填充数据来减少每次调用的开销,而不是每次都重新构建:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

作为一种替代方法,您可以将结果长度作为pad(…)方法的参数。在这种情况下,在该方法中而不是在构造函数中调整隐藏填充。

(提示:为了获得额外的学分,让它是线程安全的!: -)