java中字符串左右补齐【转】

java

/**

* 右左补齐

*/

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, 0, src.length());

for (int i = src.length(); i < len; i++) {

charr[i] = ch;

}

return new String(charr);

}

/**

* 左补齐

*/

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, diff, src.length());

for (int i = 0; i < diff; i++) {

charr[i] = ch;

}

return new String(charr);

}

调用方式:

padLeft("moon", 12, '-') ;

padRight("moon", 12, '-')

输出结果:

------------moon

moon------------

来自:https://www.cnblogs.com/preacher/p/6826585.html

以上是 java中字符串左右补齐【转】 的全部内容, 来源链接: utcz.com/z/392444.html

回到顶部