
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Left Pad a String in Java with Zeros
The following is our string −
String str = "Tim";
Now take a StringBuilder object −
StringBuilder strBuilder = new StringBuilder();
Perform left padding and extend the string length. We have set it till 20, that would include the current string as well. The zeros that will be padded comes on the left. Append the zeros here −
while (strBuilder.length() + str.length() < 10) { strBuilder.append('0'); }
The following is an example −
Example
public class Demo { public static void main(String[] args) { String str = "Tim"; StringBuilder strBuilder = new StringBuilder(); while (strBuilder.length() + str.length() < 20) { strBuilder.append('0'); } // append strBuilder.append(str); String res = strBuilder.toString(); System.out.println(res); } }
Output
0000000000000000Tim
Advertisements