Left padding a string
Question:
Write a java program that pads a string to the left.
Solution:
Here is a java example that left pads a string:
Source: (Example.java)
import org.apache.commons.lang.StringUtils;
public class Example {
public static void main(String[] args) {
String str1 = "1234567890";
System.out.println(str1);
String str2 = StringUtils.leftPad("aaa", 10);
System.out.println(str2);
String str3 = StringUtils.leftPad("bbbb", 10, "x");
System.out.println(str3);
String str4 = StringUtils.leftPad("ccccc", 10, "-");
System.out.println(str4);
}
}
Output:
$ java Example
1234567890
aaa
xxxxxxbbbb
-----ccccc
References:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#leftPad-java.lang.String-int-
Questions answered by this page:
Java Left Pad String Example