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

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


当前回答

在番石榴中,这很简单:

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

其他回答

简单的东西:

该值应该是字符串。如果不是,就转换成字符串。比如"" + 123或Integer.toString(123)

// let's assume value holds the String we want to pad
String value = "123";

子字符串从值length char索引开始,直到填充的结束长度:

String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"

更精确的

垫:

String padded = value + ("ABCDEFGH".substring(value.length())); 

// now padded is "123DEFGH"

垫左:

String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;

// now padded is "ABCDE123"

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

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

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

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

@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