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

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


当前回答

这是一个高效的实用工具类,用于Java中的左填充,右填充,中心填充和零填充字符串。

package com.example;

/**
 * Utility class for left pad, right pad, center pad and zero fill.
 */
public final class StringPadding {

    public static String left(String string, int length, char fill) {

        if (string.length() < length) {

            char[] chars = string.toCharArray();
            char[] output = new char[length];

            int delta = length - chars.length;

            for (int i = 0; i < length; i++) {
                if (i < delta) {
                    output[i] = fill;
                } else {
                    output[i] = chars[i - delta];
                }
            }

            return new String(output);
        }

        return string;
    }

    public static String right(String string, int length, char fill) {

        if (string.length() < length) {

            char[] chars = string.toCharArray();
            char[] output = new char[length];

            for (int i = 0; i < length; i++) {
                if (i < chars.length) {
                    output[i] = chars[i];
                } else {
                    output[i] = fill;
                }
            }

            return new String(output);
        }

        return string;
    }

    public static String center(String string, int length, char fill) {

        if (string.length() < length) {

            char[] chars = string.toCharArray();

            int delta = length - chars.length;
            int a = (delta % 2 == 0) ? delta / 2 : delta / 2 + 1;
            int b = a + chars.length;

            char[] output = new char[length];
            for (int i = 0; i < length; i++) {
                if (i < a) {
                    output[i] = fill;
                } else if (i < b) {
                    output[i] = chars[i - a];
                } else {
                    output[i] = fill;
                }
            }

            return new String(output);
        }

        return string;
    }

    public static String zerofill(String string, int length) {
        return left(string, length, '0');
    }

    private StringPadding() {
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "123";
        char blank = ' ';

        System.out.println("left pad:    [" + StringPadding.left(string, 10, blank) + "]");
        System.out.println("right pad:   [" + StringPadding.right(string, 10, blank) + "]");
        System.out.println("center pad:  [" + StringPadding.center(string, 10, blank) + "]");
        System.out.println("zero fill:   [" + StringPadding.zerofill(string, 10) + "]");
    }
}

输出如下:

left pad:    [       123]
right pad:   [123       ]
center pad:  [    123   ]
zero fill:   [0000000123]

其他回答

我花了一点时间才想明白。 真正的关键是阅读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);

填充到10个字符:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

输出:

  *******foo
  bar*******
  longer*than*10*chars

密码字符显示“*”:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

输出与密码字符串长度相同:

  secret123
  *********

如此:

"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")

它会用空白填充你的字符串XXX,最多9个字符。在此之后,所有空格将被替换为0。你可以把空格和0改为任何你想要的…

下面是另一种向右填充的方法:

// put the number of spaces, or any character you like, in your paddedString

String paddedString = "--------------------";

String myStringToBePadded = "I like donuts";

myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

//result:
myStringToBePadded = "I like donuts-------";

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

这与所有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);
    }
}

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