- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 a specified String in Java
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 to 20. The string that will be padded comes on the left.
while (strBuilder.length() + str.length() < 20) { strBuilder.append("demo"); }
The following is an example wherein we have left padded a string with another string “demo”
Example
public class Demo { public static void main(String[] args) { String str = "Jack"; StringBuilder strBuilder = new StringBuilder(); // left padding with a string while (strBuilder.length() + str.length() < 20) { strBuilder.append("demo"); } // append strBuilder.append(str); String res = strBuilder.toString(); System.out.println(res); } }
Output
demodemodemodemoJack
Advertisements