背景
网上找到的左右补0,基本上是对数值进行操作的,所以这里进行了优化,对自符串做处理。
网上对数值字符转化 1100这里没问题,但是 0011 转就是错误的。
方法
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 给字符串的左补0或右补0
* @param str 要处理的字符串
* @param length 补0后字符串总长度
* @param type 1-左补0 2-右补0
* @return
*/
public static String addZeroForStr(String str, int length,int type) {
int strLen = str.length();
if (strLen < length) {
while (strLen < length) {
StringBuffer sb = new StringBuffer();
if(type==1){
// 左补0
sb.append("0").append(str);
}else if(type==2){
//右补0
sb.append(str).append("0");
}
str = sb.toString();
strLen = str.length();
}
}
return str;
}
//打印
System.out.println(addZeroForStr("aa",4,1));
//结果
00aa





评论
登录后即可评论
分享你的想法,与作者互动
暂无评论