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

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


当前回答

这里有一个并行版本的你有很长的字符串:-)

int width = 100;
String s = "129018";

CharSequence padded = IntStream.range(0,width)
            .parallel()
            .map(i->i-(width-s.length()))
            .map(i->i<0 ? '0' :s.charAt(i))
            .collect(StringBuilder::new, (sb,c)-> sb.append((char)c), (sb1,sb2)->sb1.append(sb2));

其他回答

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

Java联机程序,没有花哨的库。

// 6 characters padding example
String pad = "******";
// testcases for 0, 4, 8 characters
String input = "" | "abcd" | "abcdefgh"

左Pad,不要限制

result = pad.substring(Math.min(input.length(),pad.length())) + input;
results: "******" | "**abcd" | "abcdefgh"

右移,不要限制

result = input + pad.substring(Math.min(input.length(),pad.length()));
results: "******" | "abcd**" | "abcdefgh"

左衬垫,限制衬垫长度

result = (pad + input).substring(input.length(), input.length() + pad.length());
results: "******" | "**abcd" | "cdefgh"

右垫,限制垫的长度

result = (input + pad).substring(0, pad.length());
results: "******" | "abcd**" | "abcdef"

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

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

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

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