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

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


当前回答

概括一下Eko的答案(Java 11+):

public class StringUtils {
    public static String padLeft(String s, char fill, int padSize) {
        if (padSize < 0) {
            var err = "padSize must be >= 0 (was " + padSize + ")";
            throw new java.lang.IllegalArgumentException(err);
        }

        int repeats = Math.max(0, padSize - s.length());
        return Character.toString(fill).repeat(repeats) + s;
    }

    public static String padRight(String s, char fill, int padSize) {
        if (padSize < 0) {
            var err = "padSize must be >= 0 (was " + padSize + ")";
            throw new java.lang.IllegalArgumentException(err);
        }

        int repeats = Math.max(0, padSize - s.length());
        return s + Character.toString(fill).repeat(repeats);
    }

    public static void main(String[] args) {
        System.out.println(padLeft("", 'x', 5)); // => xxxxx
        System.out.println(padLeft("1", 'x', 5)); // => xxxx1
        System.out.println(padLeft("12", 'x', 5)); // => xxx12
        System.out.println(padLeft("123", 'x', 5)); // => xx123
        System.out.println(padLeft("1234", 'x', 5)); // => x1234
        System.out.println(padLeft("12345", 'x', 5)); // => 12345
        System.out.println(padLeft("123456", 'x', 5)); // => 123456

        System.out.println(padRight("", 'x', 5)); // => xxxxx
        System.out.println(padRight("1", 'x', 5)); // => 1xxxx
        System.out.println(padRight("12", 'x', 5)); // => 12xxx
        System.out.println(padRight("123", 'x', 5)); // => 123xx
        System.out.println(padRight("1234", 'x', 5)); // => 1234x
        System.out.println(padRight("12345", 'x', 5)); // => 12345
        System.out.println(padRight("123456", 'x', 5)); // => 123456

        System.out.println(padRight("1", 'x', -1)); // => throws
    }
}

其他回答

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

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

formatter会做左右填充。不需要奇怪的第三方依赖关系(您会为如此微不足道的事情添加它们吗)。

[我省略了细节,把这篇文章做成“社区维基”,因为这不是我需要的东西。]

简单的东西:

该值应该是字符串。如果不是,就转换成字符串。比如"" + 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"

@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 

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

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

输出:

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