Below is a sample Java class that left or right pad a String.
public class PadString {
public static String leftPad(
String str,
int totalSizeOfStr,
String charToPad){
String paddedString = null;
//Check if String is null.
if (str != null)
{
StringBuilder sb = new StringBuilder();
while (sb.length() <
Math.abs(totalSizeOfStr - str.length()))
{
sb.append(charToPad);
}
paddedString = sb.toString() + str;
}
return paddedString;
}// End method
public static String rightPad(
String str,
int totalSizeOfStr,
String charToPad){
String paddedString = null;
if (str != null)
{
StringBuilder sb = new StringBuilder();
sb.append(str);
while (sb.length() <= totalSizeOfStr)
{
sb.append(charToPad);
}
paddedString = sb.toString();
}
return paddedString;
}
public static void main(String[] args) {
String str = "1234";
//Left padding
String paddedStr = leftPad(str, 10, "0");
System.out.println(paddedStr);
//Right padding
paddedStr = rightPad(str, 10, "0");
System.out.println(paddedStr);
}//End main method
}//End class
No comments:
Post a Comment