有一些简单的方法来填充字符串在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
    }
}

其他回答

你可以使用内置的StringBuilder append()和insert()方法, 对于可变字符串长度的填充:

AbstractStringBuilder append(CharSequence s, int start, int end) ;

例如:

private static final String  MAX_STRING = "                    "; //20 spaces

    Set<StringBuilder> set= new HashSet<StringBuilder>();
    set.add(new StringBuilder("12345678"));
    set.add(new StringBuilder("123456789"));
    set.add(new StringBuilder("1234567811"));
    set.add(new StringBuilder("12345678123"));
    set.add(new StringBuilder("1234567812234"));
    set.add(new StringBuilder("1234567812222"));
    set.add(new StringBuilder("12345678122334"));

    for(StringBuilder padMe: set)
        padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());

从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*

在Dzone上找到的

用零填充:

String.format("|%020d|", 93); // prints: |00000000000000000093|

让我给一些情况下的答案,你需要给左/右填充(或前缀/后缀字符串或空格)在你连接到另一个字符串之前,你不想测试长度或任何if条件。

与所选答案相同,我更喜欢Apache Commons的StringUtils,但使用这种方式:

StringUtils.defaultString(StringUtils.leftPad(myString, 1))

解释:

myString:我输入的字符串,可以为空 stringutil的。leftPad(myString, 1):如果string为空,此语句也将返回null 然后使用defaultString给出空字符串,以防止连接null

public static String LPad(String str, Integer length, char car) {
  return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
}

public static String RPad(String str, Integer length, char car) {
  return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
}

LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
RPad("Hi", 10, ' ') //gives "Hi        "
RPad("Hi", 1, ' ')  //gives "H"
//etc...