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

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


当前回答

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

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

输出:

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

其他回答

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

// 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-------";

不管怎样,我一直在寻找一些可以填充的东西,然后我决定自己编写代码。它非常简洁,你可以很容易地从中推导出padLeft和padRight

    /**
     * Pads around a string, both left and right using pad as the template, aligning to the right or left as indicated.
     * @param a the string to pad on both left and right
     * @param pad the template to pad with, it can be of any size
     * @param width the fixed width to output
     * @param alignRight if true, when the input string is of odd length, adds an extra pad char to the left, so values are right aligned
     *                   otherwise add an extra pad char to the right. When the input is of even length no extra chars will be inserted
     * @return the input param a padded around.
     */
    public static String padAround(String a, String pad, int width, boolean alignRight) {
        if (pad.length() == 0)
            throw new IllegalArgumentException("Pad cannot be an empty string!");
        int delta = width - a.length();
        if (delta < 1)
            return a;
        int half = delta / 2;
        int remainder = delta % 2;
        String padding = pad.repeat(((half+remainder)/pad.length()+1)); // repeating the padding to occupy all possible space
        StringBuilder sb = new StringBuilder(width);
//        sb.append( padding.substring(0,half + (alignRight ? 0 : remainder)));
        sb.append(padding, 0, half + (alignRight ? 0 : remainder));
        sb.append(a);
//        sb.append( padding.substring(0,half + (alignRight ? remainder : 0)));
        sb.append(padding, 0, half + (alignRight ? remainder : 0));

        return sb.toString();
    }

虽然它应该是相当快的,它可能会受益于使用一些韵母在这里和那里。

看看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();
}

很多人都有一些非常有趣的技巧,但我喜欢保持简单,所以我用这个:

public static String padRight(String s, int n, char padding){
    StringBuilder builder = new StringBuilder(s.length() + n);
    builder.append(s);
    for(int i = 0; i < n; i++){
        builder.append(padding);
    }
    return builder.toString();
}

public static String padLeft(String s, int n,  char padding) {
    StringBuilder builder = new StringBuilder(s.length() + n);
    for(int i = 0; i < n; i++){
        builder.append(Character.toString(padding));
    }
    return builder.append(s).toString();
}

public static String pad(String s, int n, char padding){
    StringBuilder pad = new StringBuilder(s.length() + n * 2);
    StringBuilder value = new StringBuilder(n);
    for(int i = 0; i < n; i++){
        pad.append(padding);
    }
    return value.append(pad).append(s).append(pad).toString();
}

这是一个高效的实用工具类,用于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]