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

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


当前回答

简单的东西:

该值应该是字符串。如果不是,就转换成字符串。比如"" + 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。格式,应该能够照顾简单的填充(例如与空格)。

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

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

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

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

我花了一点时间才想明白。 真正的关键是阅读Formatter文档。

// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X'  integral    The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);

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

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