SoFunction
Updated on 2025-05-17

How to implement string filling in Java

Java implements string filling

Method 1: Use ()

Recommended method, simple and efficient:

String str = "123";
String paddedStr = ("%06d", (str));
(paddedStr); // Output:000123

illustrate

  • %06dIndicates that the integer is formatted into a 6-bit string, and the insufficient part is filled with 0.
  • Applicable scenarios: The input is determined as a pure numeric string.

Method 2: Use DecimalFormat

Suitable for digital formatting requirements:

import ;

String str = "123";
int num = (str);
DecimalFormat df = new DecimalFormat("000000");
String paddedStr = (num);
(paddedStr); // Output:000123

illustrate

  • 000000It means that 6 bits are fixed, and 0 is not enough to be added.
  • advantage: Suitable for scenarios where numbers need to be formatted frequently.

Method 3: Manually supplement 0 (string splicing)

Flexible processing of non-numeric strings:

String str = "123";
while (() < 6) {
    str = "0" + str;
}
(str); // Output:000123

illustrate

  • Applicable scenarios: The input may contain non-numeric characters and needs to be uniformly supplemented with 0.

Method 4: Use () (Apache Commons Lang)

Dependencies need to be introduced, but powerful:

import .;

String str = "123";
String paddedStr = (str, 6, '0');
(paddedStr); // Output:000123

Depend on configuration

<dependency>
    <groupId></groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

advantage

  • Automatic processingnullInput (returnnull)。
  • Supports custom fill characters (e.g.leftPad(str, 6, ' ') fill spaces).

Method 5: Use Java 11+ ()

Elegant single-line implementation:

String str = "123";
String paddedStr = "0".repeat((0, 6 - ())) + str;
(paddedStr); // Output:000123

illustrate

  • Applicable scenarios: Java 11 and above, simple and efficient.

Summarize

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