如何在 Java 中填充字符串?

发布于 2024-07-10 21:58:13 字数 89 浏览 5 评论 0原文

有没有一些简单的方法可以在Java中填充字符串?

似乎应该在一些类似 StringUtil 的 API 中,但我找不到任何可以做到这一点的东西。

Is there some easy way to pad Strings in Java?

Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

绝影如岚 2024-07-17 21:58:13

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

Since Java 1.5, String.format() can be used to left/right pad a given string.

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) + "*");
}

And the output is:

Howto               *
               Howto*
巷雨优美回忆 2024-07-17 21:58:13

填充到 10 个字符:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

输出:

  *******foo
  bar*******
  longer*than*10*chars

为密码字符显示“*”:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

输出与密码字符串的长度相同:

  secret123
  *********

Padding to 10 characters:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

output:

  *******foo
  bar*******
  longer*than*10*chars

Display '*' for characters of password:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

output has the same length as the password string:

  secret123
  *********
孤寂小茶 2024-07-17 21:58:13

Apache StringUtils 有几种方法: leftPad, rightPad, center重复

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

Apache StringUtils has several methods: leftPad, rightPad, center and repeat.

But please note that — as others have mentioned and demonstrated in this answerString.format() and the Formatter classes in the JDK are better options. Use them over the commons code.

无法言说的痛 2024-07-17 21:58:13

Guava 中,这很简单:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');

In Guava, this is easy:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');
老娘不死你永远是小三 2024-07-17 21:58:13

简单一点:

该值应该是一个字符串。 如果不是,则将其转换为字符串。 类似于 "" + 123Integer.toString(123)

// let's assume value holds the String we want to pad
String value = "123";

子字符串从值长度字符索引开始直到填充的结束长度:

String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"

更精确

pad右:

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"

Something simple:

The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)

// let's assume value holds the String we want to pad
String value = "123";

Substring start from the value length char index until end length of padded:

String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"

More precise

pad right:

String padded = value + ("ABCDEFGH".substring(value.length())); 

// now padded is "123DEFGH"

pad left:

String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;

// now padded is "ABCDE123"
酒与心事 2024-07-17 21:58:13

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

Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).

But the algorithm is very simple (pad right up to size chars):

public String pad(String str, int size, char padChar)
{
  StringBuilder padded = new StringBuilder(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}
夜雨飘雪 2024-07-17 21:58:13

除了 Apache Commons 之外,还请参阅 String.format ,它应该能够处理简单的填充(例如使用空格)。

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).

巴黎盛开的樱花 2024-07-17 21:58:13

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

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

输出:

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

Since Java 11, String.repeat(int) can be used to left/right pad a given string.

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

Output:

*****apple
apple*****
看春风乍起 2024-07-17 21:58:13
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...
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...
黎歌 2024-07-17 21:58:13

上找到此内容:

Dzone Pad

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

Found this on Dzone

Pad with zeros:

String.format("|%020d|", 93); // prints: |00000000000000000093|
玻璃人 2024-07-17 21:58:13

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

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

可以防止 sb 的内部缓冲区增长。

i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.

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

the formatter solution is not optimal. just building the format string creates 2 new strings.

apache's solution can be improved by initializing the sb with the target size so replacing below

StringBuffer padded = new StringBuffer(str); 

with

StringBuffer padded = new StringBuffer(pad); 
padded.append(value);

would prevent the sb's internal buffer from growing.

栖竹 2024-07-17 21:58:13

这花了我一些时间才弄清楚。
真正的关键是阅读 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);

This took me a little while to figure out.
The real key is to read that Formatter documentation.

// 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);
你又不是我 2024-07-17 21:58:13

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

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

Here is another way to pad to the right:

// 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-------";
屋顶上的小猫咪 2024-07-17 21:58:13

您可以通过保留填充数据来减少每次调用的开销,而不是每次都重建它:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

作为替代方案,您可以将结果长度作为 pad(...) 方法的参数。 在这种情况下,请在该方法中而不是在构造函数中调整隐藏填充。

(提示:为了获得额外的分数,请使其线程安全!;-)

You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.

(Hint: For extra credit, make it thread-safe! ;-)

哽咽笑 2024-07-17 21:58:13

@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", '

输出:

012345678901234567890123456789
cats                          
                          cats
                cats
cats$$$$$$$$$$$$$
too long for your own good, buddy 
, 30, true)); System.out.println(pad("too long for your own good, buddy", '#', 30, true)); }

输出:

@ck's and @Marlon Tarak's answers are the only ones to use a char[], which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.

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

Simple test method:

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", '

Outputs:

012345678901234567890123456789
cats                          
                          cats
                cats
cats$$$$$$$$$$$$$
too long for your own good, buddy 
, 30, true)); System.out.println(pad("too long for your own good, buddy", '#', 30, true)); }

Outputs:

江南烟雨〆相思醉 2024-07-17 21:58:13

Java oneliners,没有花哨的库。

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

Pad Left,不限制

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

Pad Right,不限制

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

Pad Left,限制焊盘长度

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

Pad Right,限制焊盘长度

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

Java oneliners, no fancy library.

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

Pad Left, don't limit

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

Pad Right, don't limit

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

Pad Left, limit to pad length

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

Pad Right, limit to pad length

result = (input + pad).substring(0, pad.length());
results: "******" | "abcd**" | "abcdef"
瞳孔里扚悲伤 2024-07-17 21:58:13

所有字符串操作通常都需要非常高效 - 特别是当您处理大量数据时。 我想要一些快速且灵活的东西,类似于您将在 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 类本身中,那么效率将提高一倍 - 速度和内存方面。

All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.

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;
    }
}
  • note it is called with String.toCharArray() and the result can be converted to String with new String((char[])result). The reason for this is, if you applying multiple operations you can do them all on char[] and not keep on converting between formats - behind the scenes, String is stored as char[]. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.
眉目亦如画i 2024-07-17 21:58:13

java.util.Formatter 将进行左右填充。 不需要奇怪的第三方依赖项(您是否想为如此琐碎的事情添加它们)。

[我省略了详细信息,并将这篇文章设为“社区维基”,因为它不是我需要的东西。]

java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).

[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]

梦旅人picnic 2024-07-17 21:58:13

您可以使用内置的 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());

you can use the built in StringBuilder append() and insert() methods,
for padding of variable string lengths:

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

For Example:

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());
赢得她心 2024-07-17 21:58:13

这是有效的:

"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")

它将用空格填充您的字符串 XXX 最多 9 个字符。 之后所有空格都将替换为 0。您可以将空格和 0 更改为您想要的任何内容...

This works:

"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")

It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...

九局 2024-07-17 21:58:13
public static String padLeft(String in, int size, char padChar) {                
    if (in.length() <= size) {
        char[] temp = new char[size];
        /* Llenado Array con el padChar*/
        for(int i =0;i<size;i++){
            temp[i]= padChar;
        }
        int posIniTemp = size-in.length();
        for(int i=0;i<in.length();i++){
            temp[posIniTemp]=in.charAt(i);
            posIniTemp++;
        }            
        return new String(temp);
    }
    return "";
}
public static String padLeft(String in, int size, char padChar) {                
    if (in.length() <= size) {
        char[] temp = new char[size];
        /* Llenado Array con el padChar*/
        for(int i =0;i<size;i++){
            temp[i]= padChar;
        }
        int posIniTemp = size-in.length();
        for(int i=0;i<in.length();i++){
            temp[posIniTemp]=in.charAt(i);
            posIniTemp++;
        }            
        return new String(temp);
    }
    return "";
}
浅沫记忆 2024-07-17 21:58:13

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

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

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

解释:

  • myString:我输入的字符串,可以为 null
  • StringUtils .leftPad(myString, 1):如果字符串为 null,该语句也会返回 null,然后
  • 使用 defaultString 给出空字符串以防止连接 null

Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.

The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:

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

Explain:

  • myString: the string I input, can be null
  • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too
  • then use defaultString to give empty string to prevent concatenate null
妄想挽回 2024-07-17 21:58:13

使用此功能。

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

如何使用?

leftPadding(month, 2, '0');

输出:
01 02 03 04 .. 11 12

Use this function.

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

how to use?

leftPadding(month, 2, '0');

output:
01 02 03 04 .. 11 12

囍孤女 2024-07-17 21:58:13

很多人都有一些非常有趣的技术,但我喜欢保持简单,所以我采用以下方法:

public static String padRight(String s, int n, char padding){
    StringBuilder builder = new StringBuilder(s.length() + n);
    builder.append(s);
    for(int i = 0; i < n; i++){
        builder.append(padding);
    }
    return builder.toString();
}

public static String padLeft(String s, int n,  char padding) {
    StringBuilder builder = new StringBuilder(s.length() + n);
    for(int i = 0; i < n; i++){
        builder.append(Character.toString(padding));
    }
    return builder.append(s).toString();
}

public static String pad(String s, int n, char padding){
    StringBuilder pad = new StringBuilder(s.length() + n * 2);
    StringBuilder value = new StringBuilder(n);
    for(int i = 0; i < n; i++){
        pad.append(padding);
    }
    return value.append(pad).append(s).append(pad).toString();
}

A lot of people have some very interesting techniques but I like to keep it simple so I go with this :

public static String padRight(String s, int n, char padding){
    StringBuilder builder = new StringBuilder(s.length() + n);
    builder.append(s);
    for(int i = 0; i < n; i++){
        builder.append(padding);
    }
    return builder.toString();
}

public static String padLeft(String s, int n,  char padding) {
    StringBuilder builder = new StringBuilder(s.length() + n);
    for(int i = 0; i < n; i++){
        builder.append(Character.toString(padding));
    }
    return builder.append(s).toString();
}

public static String pad(String s, int n, char padding){
    StringBuilder pad = new StringBuilder(s.length() + n * 2);
    StringBuilder value = new StringBuilder(n);
    for(int i = 0; i < n; i++){
        pad.append(padding);
    }
    return value.append(pad).append(s).append(pad).toString();
}
只怪假的太真实 2024-07-17 21:58:13

这是一个高效实用程序类,用于左垫右垫中心垫零填充< /strong> 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]

This is an efficient utility class for left pad, right pad, center pad and zero fill of strings in 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) + "]");
    }
}

This is the output:

left pad:    [       123]
right pad:   [123       ]
center pad:  [    123   ]
zero fill:   [0000000123]
遮云壑 2024-07-17 21:58:13

对于那些拥有很长字符串的人来说,这是一个并行版本:-)

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

Here's a parallel version for those of you that have very long Strings :-)

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));
颜漓半夏 2024-07-17 21:58:13

稍微概括一下 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
    }
}

Generalizing Eko's answer (Java 11+) a bit:

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
    }
}
最偏执的依靠 2024-07-17 21:58:13

无论如何,我一直在寻找一些可以填充的东西,然后我决定自己编写代码。 它相当干净,您可以轻松地从中导出 padLeft 和 padRight

    /**
     * Pads around a string, both left and right using pad as the template, aligning to the right or left as indicated.
     * @param a the string to pad on both left and right
     * @param pad the template to pad with, it can be of any size
     * @param width the fixed width to output
     * @param alignRight if true, when the input string is of odd length, adds an extra pad char to the left, so values are right aligned
     *                   otherwise add an extra pad char to the right. When the input is of even length no extra chars will be inserted
     * @return the input param a padded around.
     */
    public static String padAround(String a, String pad, int width, boolean alignRight) {
        if (pad.length() == 0)
            throw new IllegalArgumentException("Pad cannot be an empty string!");
        int delta = width - a.length();
        if (delta < 1)
            return a;
        int half = delta / 2;
        int remainder = delta % 2;
        String padding = pad.repeat(((half+remainder)/pad.length()+1)); // repeating the padding to occupy all possible space
        StringBuilder sb = new StringBuilder(width);
//        sb.append( padding.substring(0,half + (alignRight ? 0 : remainder)));
        sb.append(padding, 0, half + (alignRight ? 0 : remainder));
        sb.append(a);
//        sb.append( padding.substring(0,half + (alignRight ? remainder : 0)));
        sb.append(padding, 0, half + (alignRight ? remainder : 0));

        return sb.toString();
    }

虽然它应该相当快,但它可能会从这里和那里使用一些决赛中受益。

For what it's worth, I was looking for something that would pad around and then I decided to code it myself. It's fairly clean and you can easily derive padLeft and padRight from this

    /**
     * Pads around a string, both left and right using pad as the template, aligning to the right or left as indicated.
     * @param a the string to pad on both left and right
     * @param pad the template to pad with, it can be of any size
     * @param width the fixed width to output
     * @param alignRight if true, when the input string is of odd length, adds an extra pad char to the left, so values are right aligned
     *                   otherwise add an extra pad char to the right. When the input is of even length no extra chars will be inserted
     * @return the input param a padded around.
     */
    public static String padAround(String a, String pad, int width, boolean alignRight) {
        if (pad.length() == 0)
            throw new IllegalArgumentException("Pad cannot be an empty string!");
        int delta = width - a.length();
        if (delta < 1)
            return a;
        int half = delta / 2;
        int remainder = delta % 2;
        String padding = pad.repeat(((half+remainder)/pad.length()+1)); // repeating the padding to occupy all possible space
        StringBuilder sb = new StringBuilder(width);
//        sb.append( padding.substring(0,half + (alignRight ? 0 : remainder)));
        sb.append(padding, 0, half + (alignRight ? 0 : remainder));
        sb.append(a);
//        sb.append( padding.substring(0,half + (alignRight ? remainder : 0)));
        sb.append(padding, 0, half + (alignRight ? remainder : 0));

        return sb.toString();
    }

While it should be fairly fast it could prolly benefit from using a few finals here and there.

梦幻之岛 2024-07-17 21:58:13

为此编写自己的函数可能比其他答案更简单。

private static String padRight(String str, String padChar, int n) {

    String paddedString = str;

    while (paddedString.length() < n) {

        paddedString = padChar + str;

    }

    return paddedString;

}

private static String padLeft(String str, String padChar, int n) {

    String paddedString = str;

    while (paddedString.length() < n) {

        paddedString += padChar;

    }

    return paddedString;

}

Writing your own function for this is probably simpler than other answers.

private static String padRight(String str, String padChar, int n) {

    String paddedString = str;

    while (paddedString.length() < n) {

        paddedString = padChar + str;

    }

    return paddedString;

}

private static String padLeft(String str, String padChar, int n) {

    String paddedString = str;

    while (paddedString.length() < n) {

        paddedString += padChar;

    }

    return paddedString;

}
诺曦 2024-07-17 21:58:13

对于快速而肮脏的测试,您可以使用这个:

String myString = "hello";
for(;myString.length() < 32; hello = "0" + hello); //pad left
for(;myString.length() < 32; hello += "0"); //pad rigth

我发现它有用以二进制表示形式打印长值:

String wildCardBinaryString = Long.toBinaryString(255);
for(;wildCardBinaryString.length() < 32; wildCardBinaryString = "0" + wildCardBinaryString);
System.out.println(String.format("|%s|", Long.toBinaryString(wildcard)));

它打印:

|00000000000000000000000011111111|

For a quick and dirty test you can use this:

String myString = "hello";
for(;myString.length() < 32; hello = "0" + hello); //pad left
for(;myString.length() < 32; hello += "0"); //pad rigth

I found it usefull printing a long value in a binary representation:

String wildCardBinaryString = Long.toBinaryString(255);
for(;wildCardBinaryString.length() < 32; wildCardBinaryString = "0" + wildCardBinaryString);
System.out.println(String.format("|%s|", Long.toBinaryString(wildcard)));

It prints:

|00000000000000000000000011111111|
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文