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

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


当前回答

从Java 11开始,string. repeat(int)可以用来左右填充给定的字符串。

System.out.println("*".repeat(5)+"apple");
System.out.println("apple"+"*".repeat(5));

输出:

*****apple
apple*****

其他回答

我知道这个线程有点老了,最初的问题是为了一个简单的解决方案,但如果它应该是真的很快,你应该使用字符数组。

public static String pad(String str, int size, char padChar)
{
    if (str.length() < size)
    {
        char[] temp = new char[size];
        int i = 0;

        while (i < str.length())
        {
            temp[i] = str.charAt(i);
            i++;
        }

        while (i < size)
        {
            temp[i] = padChar;
            i++;
        }

        str = new String(temp);
    }

    return str;
}

格式化程序解决方案不是最佳的。仅仅构建格式字符串就会创建2个新字符串。

Apache的解决方案可以通过用目标大小初始化sb来改进,从而替换下面的内容

StringBuffer padded = new StringBuffer(str); 

StringBuffer padded = new StringBuffer(pad); 
padded.append(value);

会阻止某人内部缓冲的增长。

另一种利用递归的解决方案。

这与所有JDK版本兼容,不需要外部库:

private static String addPadding(final String str, final int desiredLength, final String padBy) {
    String result = str;
    if (str.length() >= desiredLength) {
        return result;
    } else {
        result += padBy;
        return addPadding(result, desiredLength, padBy);
    }
}

注意:这个解决方案将附加填充,与一个小调整,你可以前缀填充值。

我花了一点时间才想明白。 真正的关键是阅读Formatter文档。

// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X'  integral    The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);

在番石榴中,这很简单:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');

你可以使用内置的StringBuilder append()和insert()方法, 对于可变字符串长度的填充:

AbstractStringBuilder append(CharSequence s, int start, int end) ;

例如:

private static final String  MAX_STRING = "                    "; //20 spaces

    Set<StringBuilder> set= new HashSet<StringBuilder>();
    set.add(new StringBuilder("12345678"));
    set.add(new StringBuilder("123456789"));
    set.add(new StringBuilder("1234567811"));
    set.add(new StringBuilder("12345678123"));
    set.add(new StringBuilder("1234567812234"));
    set.add(new StringBuilder("1234567812222"));
    set.add(new StringBuilder("12345678122334"));

    for(StringBuilder padMe: set)
        padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());