public class SamplePaddingTest { public static void main(String[] args) { System.out.println(leftPad("CAR", 10, '#')); } public static String leftPad(String theOriginalString, int length, char toPadCharacter) { String stringPaddedString = theOriginalString; while (stringPaddedString.length() < length) { stringPaddedString = toPadCharacter + stringPaddedString; } return stringPaddedString; } }Take a look at the variable theOriginalString, what's inside is the String "CAR", your int length is 10, and your toPadCharacter is the # sign. Now "String stringPaddedString = theOriginalString;" indicates that our new variable for the String "CAR" is replaced with the variable stringPaddedString. Let's break down the condition in the while loop. Consider the "stringPaddedString.length()" the length character of the String stringPaddedString which is 3, the "CAR" has 3 characters thereby making it 3. The condition inside the while is if 3 is less than 10 (which is the value of the variable int length), the toPadCharacter (#) will keep on adding to the left of the stringPaddedString ("CAR") until it reaches the condition of int length (10). This is because the called method leftpad in the main, will return the String in the left of theOriginalString until the condition is completed.
Check out the result below:
#######CAR
public class SamplePaddingTest { public static void main(String[] args) { System.out.println(leftPad("HEY", 15, '-')); } public static String leftPad(String theOriginalString, int length, char toPadCharacter) { StringBuilder sb = new StringBuilder(); while (sb.length() + theOriginalString.length() < 10) { sb.append(toPadCharacter); } sb.append(theOriginalString); String stringPaddedString = sb.toString(); return stringPaddedString; } }Check out the output of the code below:
------------HEY
public class SamplePaddingTest { public static void main(String[] args) { System.out.println(leftPad("NAME", 15, '*')); } public static String leftPad(String theOriginalString, int length, char toPadCharacter) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(toPadCharacter); } String padding = sb.toString(); String stringPaddedString = padding.substring(theOriginalString.length()) + theOriginalString; return stringPaddedString; } }What the first part of the program does is it builds the length number of pad characters (15). Now to cut the excess padding of those characters, the substring method should be performed, and after this, it should be concatenated to the set String.
Check out the expected result below:
***********NAME