forked from plusone/plusone-commons
添加字符串“补位”方法。
parent
95f625d849
commit
716cda893d
|
@ -0,0 +1,34 @@
|
|||
package xyz.zhouxy.plusone.commons.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class StrUtil {
|
||||
|
||||
public static String fillBefore(String src, int minLength, char c) {
|
||||
if (src.length() >= minLength) {
|
||||
return src;
|
||||
}
|
||||
char[] result = new char[minLength];
|
||||
Arrays.fill(result, c);
|
||||
for (int i = 1; i <= src.length(); i++) {
|
||||
result[minLength - i] = src.charAt(src.length() - i);
|
||||
}
|
||||
return String.valueOf(result);
|
||||
}
|
||||
|
||||
public static String fillAfter(String src, int length, char c) {
|
||||
if (src.length() >= length) {
|
||||
return src;
|
||||
}
|
||||
char[] result = new char[length];
|
||||
Arrays.fill(result, c);
|
||||
for (int i = 0; i < src.length(); i++) {
|
||||
result[i] = src.charAt(i);
|
||||
}
|
||||
return String.valueOf(result);
|
||||
}
|
||||
|
||||
private StrUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package xyz.zhouxy.plusone.commons.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
class StrUtilTests {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(StrUtilTests.class);
|
||||
|
||||
@Test
|
||||
void testFillZero() {
|
||||
char c = '=';
|
||||
log.info(StrUtil.fillBefore("1234", 6, c));
|
||||
log.info(StrUtil.fillBefore("12345", 6, c));
|
||||
log.info(StrUtil.fillBefore("123456", 6, c));
|
||||
log.info(StrUtil.fillBefore("1234567", 6, c));
|
||||
log.info(StrUtil.fillAfter("1234", 6, c));
|
||||
log.info(StrUtil.fillAfter("12345", 6, c));
|
||||
log.info(StrUtil.fillAfter("123456", 6, c));
|
||||
log.info(StrUtil.fillAfter("1234567", 6, c));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue