如何格式化带有前导零的 Java 字符串?

发布于 2024-09-29 22:48:18 字数 126 浏览 1 评论 0原文

例如,这是字符串:

"Apple"

我想添加零来填充 8 个字符:

"000Apple"

我该怎么做?

Here is the String, for example:

"Apple"

and I would like to add zero to fill in 8 chars:

"000Apple"

How can I do so?

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

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

发布评论

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

评论(24

夜深人未静 2024-10-06 22:48:18
public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}
public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}
云柯 2024-10-06 22:48:18

如果您必须在没有库的帮助下完成此操作:(

("00000000" + "Apple").substring("Apple".length())

只要您的字符串不超过 8 个字符,就可以。)

In case you have to do it without the help of a library:

("00000000" + "Apple").substring("Apple".length())

(Works, as long as your String isn't longer than 8 chars.)

游魂 2024-10-06 22:48:18
 StringUtils.leftPad(yourString, 8, '0');

这是来自 commons-lang参见 javadoc

 StringUtils.leftPad(yourString, 8, '0');

This is from commons-lang. See javadoc

狼亦尘 2024-10-06 22:48:18

我相信这就是他真正要求的:

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

输出:

000Apple

This is what he was really asking for I believe:

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

output:

000Apple
初吻给了烟 2024-10-06 22:48:18

您可以使用另一个答案中使用的 String.format 方法来生成 0 的字符串,

String.format("%0"+length+"d",0)

这可以通过动态调整格式字符串中前导 0 的数量来应用于您的问题:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

它仍然是一个混乱的解决方案,但具有优势您可以使用整数参数指定结果字符串的总长度。

You can use the String.format method as used in another answer to generate a string of 0's,

String.format("%0"+length+"d",0)

This can be applied to your problem by dynamically adjusting the number of leading 0's in a format string:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

It's still a messy solution, but has the advantage that you can specify the total length of the resulting string using an integer argument.

帝王念 2024-10-06 22:48:18

你可以使用这个:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")

You can use this:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
¢好甜 2024-10-06 22:48:18

使用 Guava 的 Strings 实用程序类:

Strings.padStart("Apple", 8, '0');

Using Guava's Strings utility class:

Strings.padStart("Apple", 8, '0');
a√萤火虫的光℡ 2024-10-06 22:48:18

我遇到过类似的情况,我用过这个;它非常简洁,您不必处理长度或其他库。

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

简单又整洁。字符串格式返回 " Apple" 因此在用零替换空格后,它会给出所需的结果。

I've been in a similar situation and I used this; It is quite concise and you don't have to deal with length or another library.

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

Simple and neat. String format returns " Apple" so after replacing space with zeros, it gives the desired result.

还给你自由 2024-10-06 22:48:18
String input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();
String input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();
紧拥背影 2024-10-06 22:48:18

使用 Apache Commons StringUtils.leftPad(或者查看代码来制作自己的函数)。

复制来源:

    /**
     * Left pad a String with a specified String.
     *
     * <p>Pad to a size of {@code size}.</p>
     *
     * <pre>
     * StringUtils.leftPad(null, *, *)      = null
     * StringUtils.leftPad("", 3, "z")      = "zzz"
     * StringUtils.leftPad("bat", 3, "yz")  = "bat"
     * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
     * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
     * StringUtils.leftPad("bat", 1, "yz")  = "bat"
     * StringUtils.leftPad("bat", -1, "yz") = "bat"
     * StringUtils.leftPad("bat", 5, null)  = "  bat"
     * StringUtils.leftPad("bat", 5, "")    = "  bat"
     * </pre>
     *
     * @param str  the String to pad out, may be null
     * @param size  the size to pad to
     * @param padStr  the String to pad with, null or empty treated as single space
     * @return left padded String or original String if no padding is necessary,
     *  {@code null} if null String input
     */
    public static String leftPad(final String str, final int size, String padStr) {
        if (str == null) {
            return null;
        }
        if (isEmpty(padStr)) {
            padStr = SPACE;
        }
        final int padLen = padStr.length();
        final int strLen = str.length();
        final int pads = size - strLen;
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (padLen == 1 && pads <= PAD_LIMIT) {
            return leftPad(str, size, padStr.charAt(0));
        }

        if (pads == padLen) {
            return padStr.concat(str);
        }
        if (pads < padLen) {
            return padStr.substring(0, pads).concat(str);
        }
        final char[] padding = new char[pads];
        final char[] padChars = padStr.toCharArray();
        for (int i = 0; i < pads; i++) {
            padding[i] = padChars[i % padLen];
        }
        return new String(padding).concat(str);
    }

Use Apache Commons StringUtils.leftPad (or look at the code to make your own function).

Copied Source:

    /**
     * Left pad a String with a specified String.
     *
     * <p>Pad to a size of {@code size}.</p>
     *
     * <pre>
     * StringUtils.leftPad(null, *, *)      = null
     * StringUtils.leftPad("", 3, "z")      = "zzz"
     * StringUtils.leftPad("bat", 3, "yz")  = "bat"
     * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
     * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
     * StringUtils.leftPad("bat", 1, "yz")  = "bat"
     * StringUtils.leftPad("bat", -1, "yz") = "bat"
     * StringUtils.leftPad("bat", 5, null)  = "  bat"
     * StringUtils.leftPad("bat", 5, "")    = "  bat"
     * </pre>
     *
     * @param str  the String to pad out, may be null
     * @param size  the size to pad to
     * @param padStr  the String to pad with, null or empty treated as single space
     * @return left padded String or original String if no padding is necessary,
     *  {@code null} if null String input
     */
    public static String leftPad(final String str, final int size, String padStr) {
        if (str == null) {
            return null;
        }
        if (isEmpty(padStr)) {
            padStr = SPACE;
        }
        final int padLen = padStr.length();
        final int strLen = str.length();
        final int pads = size - strLen;
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (padLen == 1 && pads <= PAD_LIMIT) {
            return leftPad(str, size, padStr.charAt(0));
        }

        if (pads == padLen) {
            return padStr.concat(str);
        }
        if (pads < padLen) {
            return padStr.substring(0, pads).concat(str);
        }
        final char[] padding = new char[pads];
        final char[] padChars = padStr.toCharArray();
        for (int i = 0; i < pads; i++) {
            padding[i] = padChars[i % padLen];
        }
        return new String(padding).concat(str);
    }
勿挽旧人 2024-10-06 22:48:18

您可以使用:

String.format("%08d", "Apple");

这似乎是最简单的方法,不需要任何外部库。

You can use:

String.format("%08d", "Apple");

It seems to be the simplest method and there is no need of any external library.

心安伴我暖 2024-10-06 22:48:18

在 Java 中:

String zeroes="00000000";
String apple="apple";

String result=zeroes.substring(apple.length(),zeroes.length())+apple;

在 Scala 中:

"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}

您还可以在 Java 8 中探索一种使用流和化简来完成此操作的方法(类似于我使用 Scala 的方式)。它与所有其他解决方案有点不同,我特别喜欢它。

In Java:

String zeroes="00000000";
String apple="apple";

String result=zeroes.substring(apple.length(),zeroes.length())+apple;

In Scala:

"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}

You can also explore a way in Java 8 to do it using streams and reduce (similar to the way I did it with Scala). It's a bit different to all the other solutions and I particularly like it a lot.

会发光的星星闪亮亮i 2024-10-06 22:48:18

使用 String::repeat 方法的解决方案(Java 11)

String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;

如果需要,将 8 更改为另一个数字或将其参数化

Solution with method String::repeat (Java 11)

String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;

If needed change 8 to another number or parameterize it

就此别过 2024-10-06 22:48:18

我喜欢 Pad a String with Zeros 的解决方案,

String.format("%1$" + length + "s", inputString).replace(' ', '0');

长度 = "8" 和 inputString =“苹果”

I like the solution from Pad a String with Zeros

String.format("%1
quot; + length + "s", inputString).replace(' ', '0');

with length = "8" and inputString = "Apple"

森林迷了鹿 2024-10-06 22:48:18
public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}
public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}
勿忘初心 2024-10-06 22:48:18

您可能需要处理边缘情况。这是一个通用方法。

public class Test {
    public static void main(String[] args){
        System.out.println(padCharacter("0",8,"hello"));
    }
    public static String padCharacter(String c, int num, String str){
        for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
        return str;
    }
}

You may have to take care of edgecase. This is a generic method.

public class Test {
    public static void main(String[] args){
        System.out.println(padCharacter("0",8,"hello"));
    }
    public static String padCharacter(String c, int num, String str){
        for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
        return str;
    }
}
只怪假的太真实 2024-10-06 22:48:18
public static void main(String[] args)
{
    String stringForTest = "Apple";
    int requiredLengthAfterPadding = 8;
    int inputStringLengh = stringForTest.length();
    int diff = requiredLengthAfterPadding - inputStringLengh;
    if (inputStringLengh < requiredLengthAfterPadding)
    {
        stringForTest = new String(new char[diff]).replace("\0", "0")+ stringForTest;
    }
    System.out.println(stringForTest);
}
public static void main(String[] args)
{
    String stringForTest = "Apple";
    int requiredLengthAfterPadding = 8;
    int inputStringLengh = stringForTest.length();
    int diff = requiredLengthAfterPadding - inputStringLengh;
    if (inputStringLengh < requiredLengthAfterPadding)
    {
        stringForTest = new String(new char[diff]).replace("\0", "0")+ stringForTest;
    }
    System.out.println(stringForTest);
}
草莓味的萝莉 2024-10-06 22:48:18
public static String lpad(String str, int requiredLength, char padChar) {
    if (str.length() > requiredLength) {
        return str;
    } else {
        return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
    }
}
public static String lpad(String str, int requiredLength, char padChar) {
    if (str.length() > requiredLength) {
        return str;
    } else {
        return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
    }
}
情深已缘浅 2024-10-06 22:48:18

有没有人尝试过这个纯Java解决方案(没有SpringUtils):

//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros. 
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string. 
String.format("%1$10s", "mystring" ).replace(" ","0");

不幸的是,这个解决方案只有在字符串中没有空格的情况下才有效。

Did anyone tried this pure Java solution (without SpringUtils):

//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros. 
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string. 
String.format("%1$10s", "mystring" ).replace(" ","0");

Unfortunately this solution works only if you do not have blank spaces in a string.

半葬歌 2024-10-06 22:48:18

这很快&适用于任何长度。

public static String prefixZeros(String value, int len) {
    char[] t = new char[len];
    int l = value.length();
    int k = len-l;
    for(int i=0;i<k;i++) { t[i]='0'; }
    value.getChars(0, l, t, k);
    return new String(t);
}

This is fast & works for whatever length.

public static String prefixZeros(String value, int len) {
    char[] t = new char[len];
    int l = value.length();
    int k = len-l;
    for(int i=0;i<k;i++) { t[i]='0'; }
    value.getChars(0, l, t, k);
    return new String(t);
}
握住我的手 2024-10-06 22:48:18

字符串中的大多数字符只有 8 个字符,

int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);

可以比 Chris Lercher 回答 更快,因为在我的机器上, 速度快 1/8 。

Can be faster then Chris Lercher answer when most of in String have exacly 8 char

int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);

in my case on my machine 1/8 faster.

っ〆星空下的拥抱 2024-10-06 22:48:18

这是我用来预填充字符串的简单的无 API“可读脚本”版本。 (简单、可读且可调整)。

while(str.length() < desired_length)
  str = '0'+str;

Here is the simple API-less "readable script" version I use for pre-padding a string. (Simple, Readable, and Adjustable).

while(str.length() < desired_length)
  str = '0'+str;
薄暮涼年 2024-10-06 22:48:18

如果你想用纯Java编写程序,你可以按照下面的方法,或者有很多String Utils可以帮助你更好地使用更高级的功能。

使用简单的静态方法,您可以实现这一点,如下所示。

public static String addLeadingText(int length, String pad, String value) {
    String text = value;
    for (int x = 0; x < length - value.length(); x++) text = pad + text;
    return text;
}

您可以使用上述方法 addLeadingText(length, padding text, your text)

addLeadingText(8, "0", "Apple");

输出将为 000Apple

If you want to write the program in pure Java you can follow the below method or there are many String Utils to help you better with more advanced features.

Using a simple static method you can achieve this as below.

public static String addLeadingText(int length, String pad, String value) {
    String text = value;
    for (int x = 0; x < length - value.length(); x++) text = pad + text;
    return text;
}

You can use the above method addLeadingText(length, padding text, your text)

addLeadingText(8, "0", "Apple");

The output would be 000Apple

前事休说 2024-10-06 22:48:18

它不漂亮,但很有效。如果您可以访问 apache commons 我建议使用它

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}

It isn't pretty, but it works. If you have access apache commons i would suggest that use that

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文