Formatting with Java LPAD and RPAD. Fill in the specified characters on the left and right of the string.
Javaand then use the SQL functionLPAD, ,RPADHere is a sample source that performs the same process as
These arefixed length formatThis is very useful when dealing with
- LPAD... Returns a string with a repeated string filled in on the left side of the string so that the total number of characters is the specified number of digits.
- RPAD... Returns a string with a repeated string filled in on the right side of the string so that the total number of characters is the specified number of digits.
sample program
/**
* Perform RPAD.
* Add the specified string [addStr] to the right of the string [str] to [len]
* Insert until full.
* @param str target string
* @param len Number of digits to refill (specifies the size after performing RPAD)
* @param addStr String to insert
* @return The string after conversion.
*/
public static String rpad(String str, int len, String addStr) {
return fillString(str, “R”, len, addStr);
}
/**
* Add the string [addStr] to be added to the string [str]
* Insert at [position] until [len] is filled.
*
* *Even if [str] is null or an empty literal, use [addStr]
* Returns the result inserted until [len] is filled.
* @param str target string
* @param position Insert before ⇒ L or l Insert after ⇒ R or r
* @param len Number of digits to replenish
* @param addStr String to insert
* @return The string after conversion.
*/
public static String fillString(String str, String position,
int len,
String addStr) {
if (addStr == null || addStr.length() == 0) {
throw new IllegalArgumentException
(“The value of the string to be inserted is invalid. addStr=”+addStr);
}
if (str == null) {
str = “”;
}
StringBuffer buffer = new StringBuffer(str);
while (len > buffer.length()) {
if (position.equalsIgnoreCase(“l”)) {
int sum = buffer.length() + addStr.length();
if (sum > len) {
addStr = addStr.substring
(0,addStr.length() – (sum – len));
buffer.insert(0, addStr);
}else{
buffer.insert(0, addStr);
}
} else {
buffer.append(addStr);
}
}
if (buffer.length() == len) {
return buffer.toString();
}
return buffer.toString().substring(0, len);
}
Execution Result
◆Example of Execution
public static void main(String[] args) { // For lpad, fill in the spaces to the left until there are 5 digits. String ret = lpad("abc", 5 , " "); System.out.println("'" + ret + "'"); // For rpad. fill space to the right until 5 digits. ret = rpad("abc", 5 , " "); System.out.println("'" + ret + "'"); // If null ret = rpad(null, 5 , " "); System.out.println("'" + ret + "'"); // if null }
◆Output result
'abc' ' 'abc ' ' '