代码:
package fixsizestring; public class TestClass { public static void main(String[] args) { for(int i=0;i<10;i++) { System.out.println(fixSizeStr("#"+i,10)+fixSizeStr("abcdefg",10)+fixSizeStr("北32京32",10)+fixSizeStr("广202州",10)+fixSizeStr(null,10)); System.out.println(fixSizeStr2("."+i,10)+fixSizeStr2("abcdefg",10)+fixSizeStr2("北32京32",10)+fixSizeStr2("福322州",10)+fixSizeStr2(null,10)); } } // 得到一定长度的字符串,不足补空格 private static String fixSizeStr(Object obj, int size) { String str; if(obj==null) { str="null"; }else { str=obj.toString(); } int strLen; if (obj == null) { strLen = 0; }else{ strLen= str.length(); } if (strLen == size) { return str; } else if (strLen < size) { int temp = size - strLen; String tem = ""; for (int i = 0; i < temp; i++) { tem = tem + " "; } return str + tem; }else{ return str.substring(0,size); } } // 得到一定长度的字符串,不足补空格 private static String fixSizeStr2(Object obj, int size) { String str; if(obj==null) { str="null"; }else { str=obj.toString(); } return String.format("%-"+size+"s", str); } }
输出:
#0 abcdefg 北32京32 广202州 null .0 abcdefg 北32京32 福322州 null #1 abcdefg 北32京32 广202州 null .1 abcdefg 北32京32 福322州 null #2 abcdefg 北32京32 广202州 null .2 abcdefg 北32京32 福322州 null #3 abcdefg 北32京32 广202州 null .3 abcdefg 北32京32 福322州 null #4 abcdefg 北32京32 广202州 null .4 abcdefg 北32京32 福322州 null #5 abcdefg 北32京32 广202州 null .5 abcdefg 北32京32 福322州 null #6 abcdefg 北32京32 广202州 null .6 abcdefg 北32京32 福322州 null #7 abcdefg 北32京32 广202州 null .7 abcdefg 北32京32 福322州 null #8 abcdefg 北32京32 广202州 null .8 abcdefg 北32京32 福322州 null #9 abcdefg 北32京32 广202州 null .9 abcdefg 北32京32 福322州 null
--END-- 2019-12-06 13:59