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

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


当前回答

除了Apache Commons,还请参阅String。格式,应该能够照顾简单的填充(例如与空格)。

其他回答

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

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

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

Apache StringUtils有几个方法:leftPad, rightPad, center和repeat。

但是请注意,正如其他人在这个回答中提到和演示的那样,JDK中的String.format()和Formatter类是更好的选择。使用它们而不是公共代码。

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

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);

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

使用该函数。

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

从Java 1.5开始,string. format()可以用于左/右填充给定的字符串。

public static String padRight(String s, int n) {
     return String.format("%-" + n + "s", s);  
}

public static String padLeft(String s, int n) {
    return String.format("%" + n + "s", s);  
}

...

public static void main(String args[]) throws Exception {
 System.out.println(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 20) + "*");
}

输出为:

Howto               *
               Howto*