SoFunction
Updated on 2025-04-13

Detailed explanation of java string numbers filling digits

Java string numbers fill in digits

There are several common methods to implement string bit complementation in Java, which can be selected and used according to different scenarios:

1. Use the () method

  • 1‌. Fill the left (filling the space on the right)‌
String result = ("%10s", "hello"); // Total length10,Make up spaces on the left‌:ml-citation{ref="5" data="citationList"}
  • ‌2. Right aligned (left side zero)‌
String str = ("%06d", 12345); // Output"012345"‌:ml-citation{ref="5,7" data="citationList"}
  • ‌3. Custom complement characters

Implement other characters by replacing spaces:

String res = ("%5s", "gr").replace(' ', '1'); // Output"111gr"‌:ml-citation{ref="4" data="citationList"}

2. Apache Commons Lang library method

  • Use() to achieve left complementation:
String value = ("3123123", 10, "0"); // Output"0003123123"‌:ml-citation{ref="4" data="citationList"}

3. Java 11+ () method

  • Applicable to specific characters that are known to be supplemented:
String padding = " ".repeat(16 - ());
String result = originalStr + padding; // Make the space right to16Bit‌:ml-citation{ref="3" data="citationList"}

4. Loop traversal implementation

  • Dynamically build a complement string through StringBuilder:
public static String padString(String input, char padChar, int length) {
    StringBuilder result = new StringBuilder(input);
    while (() < length) {
        (0, padChar); // Left complement specified character ‌:ml-citation{ref="1" data="citationList"}    }
    return ();
}

5. NumberFormat digital formatting

  • Suitable for numeric types to make up zero:
NumberFormat nf = ();
(6); // Set the minimum number of integer digitsString formatted = (123); // Output"000123"‌:ml-citation{ref="5" data="citationList"}

Select suggestions:

  • Native recommendation: Use() first, the code is concise and the performance is good‌57
  • ‌Third-party library scenario‌: If Apache Commons Lang has been introduced into the project, recommend ()‌4
  • ‌Extra-long replacement requirement‌: Java 11+’s repeat() method is more efficient‌3
  • ‌Historical Compatibility‌: Lower versions of Java can be implemented using loop traversal‌12

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.