格式化方法
public static String insert(String string, String symbol, boolean overflowStrategy, int... index) {
if (StringUtils.isEmpty(string) || StringUtils.isEmpty(symbol) || ArrayUtils.isEmpty(index)) {
return string;
}
StringBuilder result = new StringBuilder(string);
int symbolLength = StringUtils.length(symbol);
int offset = 0;
for (int i : index) {
offset += i;
if (offset > result.length()) {
if (overflowStrategy) {
result.insert(result.length(), symbol);
}
break;
}
result.insert(offset, symbol);
offset += symbolLength;
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(insert("15900001111", "-", Boolean.FALSE, 3, 4));
System.out.println(insert("6214862112345678", "-", Boolean.FALSE, 4, 4, 4));
System.out.println(insert("1223334444", "-", Boolean.FALSE, 1, 2, 3));
System.out.println(insert("1223334444", "-", Boolean.TRUE, 1, 2, 3, 5));
}
测试结果
159-0000-1111
6214-8621-1234-5678
1-22-333-4444
1-22-333-4444-