Home >Java >javaTutorial >How Can I Left-Pad a String with Zeros in Java?

How Can I Left-Pad a String with Zeros in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 06:35:14966browse

How Can I Left-Pad a String with Zeros in Java?

Left Zero Padding a String

While similar questions exist, let's address the specific method for left padding a string with zeros.

Desired Output

Given an input string "129018", the desired output is "0000129018," where the total output length is ten.

Method for String with Numbers

If your string consists solely of numbers, an effective method is to convert it to an integer and apply zero padding. This can be done using String.format() as follows:

String myString = "129018";
String paddedString = String.format("%010d", Integer.parseInt(myString));

In this example, 0d specifies that the resulting string should be 10 characters long, with leading zeros added if necessary.

Method for Non-Numeric Strings

For strings containing non-numeric characters, the String.format() approach cannot be used. In such cases, you can manually left-pad the string with zeros using string concatenation:

String myString = "hello";
int desiredLength = 10;
String paddedString = "";

// Pad with the required number of zeros
for (int i = myString.length(); i < desiredLength; i++) {
    paddedString += "0";
}

// Append the original string to the padded portion
paddedString += myString;

The above is the detailed content of How Can I Left-Pad a String with Zeros in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn