1.在C#中PadLeft()方法简单来说就是字符串长度不顾指定数值时在左边用指定符号补全。比如"a".PadLeft(3,"0"),执行结果就是"00a",在java中如何实现这种效果呢?以下PadLeftOrRightUtil ()工具类就提供了字符串左右对齐的方法。
public class PadLeftOrRightUtil {
/**
* String左对齐
* src :字符串
* len:满足长度
* ch:补充字符
*/
public static String padLeft(String src, int len, char ch) {
int diff = len - src.length();
if (diff <= 0) {
return src;
}
char[] charr = new char[len];
System.arraycopy(src.toCharArray(), 0, charr, 0, src.length());
for (int i = src.length(); i < len; i++) {
charr[i] = ch;
}
return new String(charr);
}
/**
* String右对齐
* src :字符串
* len:满足长度
* ch:补充字符
*/
public static String padRight(String src, int len, char ch) {
int diff = len - src.length();
if (diff <= 0) {
return src;
}
char[] charr = new char[len];
System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());
for (int i = 0; i < diff; i++) {
charr[i] = ch;
}
return new String(charr);
}
}