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 with spaces (' ') in Java
Let us see an example first to understand how a string looks with left padding −
demotext //left padding with spaces 0000000demotext //left padding with 7 zeros
The following is our string −
String str = "Jack";
Now take a StringBuilder object −
StringBuilder strBuilder = new StringBuilder();
Perform left padding and extend the string length. The spaces that will be padded comes on the left. Append the spaces here −
while (strBuilder.length() + str.length() < 10) {
strBuilder.append(' ');
}
The following is an example to pad a string to the left with spaces
Example
public class Demo {
public static void main(String[] args) {
String str = "Jack";
StringBuilder strBuilder = new StringBuilder();
// left padding with spaces
while (strBuilder.length() + str.length() < 10) {
strBuilder.append(' ');
}
// append
strBuilder.append(str);
String res = strBuilder.toString();
System.out.println(res);
}
}
Output
Jack
Advertisements