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

 

今天在处理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));
	}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值