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

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


当前回答

所有的字符串操作通常都需要非常高效——特别是当你处理大数据集的时候。我想要的东西是快速和灵活的,类似于你将在plsql pad命令。另外,我不想为一件小事包含一个巨大的库。考虑到这些因素,这些解决方案都不令人满意。这是我提出的解决方案,有最好的基准测试结果,如果有人可以改进它,请添加您的评论。

public static char[] lpad(char[] pStringChar, int pTotalLength, char pPad) {
    if (pStringChar.length < pTotalLength) {
        char[] retChar = new char[pTotalLength];
        int padIdx = pTotalLength - pStringChar.length;
        Arrays.fill(retChar, 0, padIdx, pPad);
        System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
        return retChar;
    } else {
        return pStringChar;
    }
}

注意它是用String. tochararray()调用的,结果可以用new String((char[])result)转换为String。这样做的原因是,如果你应用多个操作,你可以在char[]上完成它们,而不需要在格式之间进行转换——在幕后,字符串存储为char[]。如果这些操作包含在String类本身中,那么效率将提高一倍——速度和内存方面。

其他回答

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

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

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

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

我花了一点时间才想明白。 真正的关键是阅读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);

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

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

@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