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 a specified character in Java
The following is our string −
String str = "Amit";
Now take a StringBuilder object −
StringBuilder strBuilder = new StringBuilder();
Set the character you want to pad with a string −
Character ch = '^';
Perform left padding and extend the string length to 5 (one for the additional character). The character that will be padded comes on the left −
while (strBuilder.length() + str.length() < 5) {
strBuilder.append(ch);
}
The following is an example −
Example
public class Demo {
public static void main(String[] args) {
String str = "Amit";
Character ch = '^';
StringBuilder strBuilder = new StringBuilder();
while (strBuilder.length() + str.length() < 5) {
strBuilder.append(ch);
}
// append
strBuilder.append(str);
String res = strBuilder.toString();
System.out.println(res);
}
}
Output
^Amit
Advertisements