java字符串拼接指定内容-左右组合(leftright padding)

xiaoxiao2021-02-28  111

今天在处理ID时,又一次碰到了字符串的左右拼接问题。相信很多人都有经历。

我们还是熟悉下需求,还是那句话。需求相同才是可用的解决方案。

我们需要在某个字符串的左边填充0,总长度为10位,或者右边填充0,总长度为0,或者,前后的内容固定,中间需要填充0.

String没有left padding ,right padding的函数。。那只有自己写了。。

代码性能没有测试,但是自己感觉还行。

上代码。(英语较烂,凑合看)

/** * get left padding String with specification char for existed suffix * for example,if need left padding zero for some String, * like left padding 0 to 12,and need total length 10, * then the result will be 0000000012. * * @param suffix * the suffix for return String * @param fill * the fill char for String * @param totalLength * the total length need for composite String * @return */ public static String getLeftPadding(String suffix,char fill,int totalLength){ return getFillString("",suffix,fill,totalLength); } /** * get right padding String with specification char for existed prefix * for example,if need left padding zero for some String, * like right padding 0 to A,and need total length 10, * then the result will be A000000000. * * @param prefix * the prefix for return String * @param fill * the fill char for String * @param totalLength * the total length need for composite String * @return */ public static String getRightPadding(String prefix,char fill,int totalLength){ return getFillString(prefix,"",fill,totalLength); } /** * get char fill composite String for existed prefix or suffix * for example,if need left padding zero for some String, * like padding 0 to 12,and need total length 10, * then the result will be 0000000012. what's more, * if add a prefix for this composite String,like A, * then then return String will be A000000012. * * @param prefix * the prefix for return String * @param suffix * the suffix for return String * @param fill * the fill char for String * @param totalLength * the total length need for composite String * @return */ public static String getFillString(String prefix,String suffix,char fill,int totalLength){ int c = 0; int needLength = totalLength - (prefix.length()+suffix.length()); StringBuilder sb = new StringBuilder(); sb.append(prefix); while(c < needLength){ sb.append(fill); c++; } sb.append(suffix); return sb.toString(); } public static void main(String[] args) { System.out.println(getFillString("A","1",'0',10)); System.out.println(getLeftPadding("1",'0',10)); System.out.println(getRightPadding("A",'0',10)); }

转载请注明原文地址: https://www.6miu.com/read-19321.html

最新回复(0)