replace方法支持包含增补字符(例如:𤰉)的字符串。脱敏等依赖该方法处理形如"𤰉秀秀"的中文时处理异常。

This commit is contained in:
micuncang 2021-12-25 23:25:44 +08:00
parent ce504c2a3e
commit 1b63807965
2 changed files with 20 additions and 7 deletions

View File

@ -3583,27 +3583,29 @@ public class CharSequenceUtil {
if (isEmpty(str)) { if (isEmpty(str)) {
return str(str); return str(str);
} }
final int strLength = str.length(); String originalStr = str(str);
int[] strCodePoints = originalStr.codePoints().toArray();
final int strLength = strCodePoints.length;
if (startInclude > strLength) { if (startInclude > strLength) {
return str(str); return originalStr;
} }
if (endExclude > strLength) { if (endExclude > strLength) {
endExclude = strLength; endExclude = strLength;
} }
if (startInclude > endExclude) { if (startInclude > endExclude) {
// 如果起始位置大于结束位置不替换 // 如果起始位置大于结束位置不替换
return str(str); return originalStr;
} }
final char[] chars = new char[strLength]; final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strLength; i++) { for (int i = 0; i < strLength; i++) {
if (i >= startInclude && i < endExclude) { if (i >= startInclude && i < endExclude) {
chars[i] = replacedChar; stringBuilder.append(replacedChar);
} else { } else {
chars[i] = str.charAt(i); stringBuilder.append(new String(strCodePoints, i, 1));
} }
} }
return new String(chars); return stringBuilder.toString();
} }
/** /**

View File

@ -235,6 +235,17 @@ public class StrUtilTest {
Assert.assertEquals("103", result1); Assert.assertEquals("103", result1);
} }
@Test
public void replaceTest5() {
String a = "\uD853\uDC09秀秀";
String result = StrUtil.replace(a, 1, a.length(), '*');
Assert.assertEquals("\uD853\uDC09**", result);
String aa = "规划大师";
String result1 = StrUtil.replace(aa, 2, a.length(), '*');
Assert.assertEquals("规划**", result1);
}
@Test @Test
public void upperFirstTest() { public void upperFirstTest() {
StringBuilder sb = new StringBuilder("KEY"); StringBuilder sb = new StringBuilder("KEY");