Write function to prepend string in Java


import java.util.*; import java.lang.*; import java.io.*; class StringUtils { /** * Method to PrePend String */ public static String prependString(String source, String pad, int length) { if (source == null) { return null; } if (pad == null) { return source; } StringBuffer result = new StringBuffer(); result.append(source); while (result.length() < length) { result.insert(0, pad); } return result.toString(); } public static void main (String[] args) throws java.lang.Exception { // prepend zeros to a number if total digits of the number is less than 5. String prepend = "0"; int fixedLength = 5; String num1 = "123"; String num1Fixed = StringUtils.prependString(num1,prepend,fixedLength); System.out.println(num1Fixed); String num2 = "1"; String num2Fixed = StringUtils.prependString(num2,prepend,fixedLength); System.out.println(num2Fixed); } }

Loading Please Wait...