Padding String in Salesforce Apex

Left Pad:

leftPad(length): Returns the current String padded with spaces on the left and of the specified length. If length is less than or equal to the current String size, the entire String is returned without space padding.

String name = 'biswa';
String lpName = name.leftPad(8);
System.debug('LeftPad-' + lpName);
System.assertEquals('   biswa', lpName);

leftPad(length, padStr): Returns the current String padded with String padStr on the left and of the specified length. padStr to pad with; if null or empty treated as single blank.

Integer num = 555;
String lpString = String.valueOf(num).leftPad(5, '0');
System.debug('LeftPad-' + lpString);
System.assertEquals('00555', lpString);

Right Pad:

rightPad(length): Returns the current String padded with spaces on the right and of the specified length. If length is less than or equal to the current String size, the entire String is returned without space padding.

String name = 'biswa';
String rpName = name.rightPad(8);
System.debug('RightPad-' + rpName);
System.assertEquals('biswa   ', rpName);

rightPad(length, padStr): Returns the current String padded with String padStr on the right and of the specified length. padStr to pad with; if null or empty treated as single blank.

Integer num = 555;
String rpString = String.valueOf(num).rightPad(5, '0');
System.debug('RightPad-' + rpString);
System.assertEquals('55500', rpString);