題目描述:app
分析:由樣例可知,第二個參數表示要返回的字符串的最小長度,因此當給定字符串的長度小於規定字符串最小長度時就在左邊填充空格,另外還有一個重載方法leftpad的第三個參數指定左邊填充的字符。須要注意的是:只有但字符串長度小於規定的字符串最小長度時才須要左填充,不然,直接返回原字符串。ide
個人代碼:spa
1 public class StringUtils { 2 /** 3 * @param originalStr: the string we want to append to with spaces 4 * @param size: the target length of the string 5 * @return: A string 6 */ 7 static public String leftPad(String originalStr, int size) { 8 int n; 9 if(originalStr == null) { 10 n =0; 11 }else { 12 n = originalStr.length(); 13 } 14 //當字符串長度大於等於size時,直接返回原字符串 15 if(n >= size) { 16 return originalStr; 17 }else { 18 n = size - n; 19 for(int i=0; i<n; i++) { 20 originalStr = " "+originalStr; 21 } 22 return originalStr; 23 } 24 } 25 26 /* 27 * @param originalStr: the string we want to append to 28 * @param size: the target length of the string 29 * @param padChar: the character to pad to the left side of the string 30 * @return: A string 31 */ 32 static public String leftPad(String originalStr, int size, char padChar) { 33 int n; 34 if(originalStr == null) { 35 n =0; 36 }else { 37 n = originalStr.length(); 38 } 39 if(n >= size) { 40 return originalStr; 41 }else { 42 n = size - n; 43 for(int i=0; i<n; i++) { 44 originalStr = padChar+originalStr; 45 } 46 return originalStr; 47 } 48 } 49 }