mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
replace方法支持包含增补字符(例如:𤰉)的字符串。脱敏等依赖该方法处理形如"𤰉秀秀"的中文时处理异常。
This commit is contained in:
parent
ce504c2a3e
commit
1b63807965
@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -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");
|
||||||
|
Loading…
x
Reference in New Issue
Block a user