Home >Java >javaTutorial >How to Left-Pad a String with Zeros in Java?
Left Padding a String with Zeros in Java
Similar inquiries have been discussed in the past, but there remains some ambiguity regarding the technique for left padding a string with zeros. Specifically, let's aim to achieve the following transformation:
Input: "129018"
Output: "0000129018"
The final output should consist of exactly ten characters.
Numeric Strings
For strings containing only numeric characters, a simple approach is to convert the string to an integer and then use the String.format method to apply left padding:
String input = "129018"; int number = Integer.parseInt(input); String padded = String.format("%010d", number);
Non-Numeric Strings
For non-numeric strings, alternative approaches are required:
String Concatenation
You can concatenate the required number of zeros to the beginning of the string:
String input = "abc"; StringBuilder padded = new StringBuilder(); int paddingLength = 10 - input.length(); for (int i = 0; i < paddingLength; i++) { padded.append('0'); } padded.append(input);
Substring Replacement
You can replace a substring of the appropriate length at the beginning of the string with zeros:
String input = "abc"; String padded = String.format("%10s", input).replaceFirst(" ", "0");
StringBuilder Transformation
You can create a StringBuilder from the existing string and insert zeros at the beginning:
String input = "abc"; StringBuilder padded = new StringBuilder(input); for (int i = 0; i < 10 - input.length(); i++) { padded.insert(0, '0'); }
The above is the detailed content of How to Left-Pad a String with Zeros in Java?. For more information, please follow other related articles on the PHP Chinese website!