add method

This commit is contained in:
Looly 2022-01-27 20:35:02 +08:00
parent e02d599964
commit cafc9d985d
4 changed files with 49 additions and 0 deletions

View File

@ -14,6 +14,7 @@
* 【core 】 CsvWriter修改规则去除末尾多余换行符issue#I4RSQY@Gitee
* 【core 】 DateUtil增加rangeFunc和rangeConsumeissue#I4RSQY@Gitee
* 【core 】 DateTime增加setUseJdkToStringStyle方法
* 【core 】 CharSequenceUtil增加replace重载(issue#2122@Github)
### 🐞Bug修复
* 【core 】 修复ChineseDate农历获取正月出现数组越界BUGissue#2112@Github

View File

@ -3601,6 +3601,46 @@ public class CharSequenceUtil {
return stringBuilder.toString();
}
/**
* 替换指定字符串的指定区间内字符为指定字符串字符串只重复一次<br>
* 此方法使用{@link String#codePoints()}完成拆分替换
*
* @param str 字符串
* @param startInclude 开始位置包含
* @param endExclude 结束位置不包含
* @param replacedStr 被替换的字符串
* @return 替换后的字符串
* @since 3.2.1
*/
public static String replace(CharSequence str, int startInclude, int endExclude, CharSequence replacedStr) {
if (isEmpty(str)) {
return str(str);
}
final String originalStr = str(str);
int[] strCodePoints = originalStr.codePoints().toArray();
final int strLength = strCodePoints.length;
if (startInclude > strLength) {
return originalStr;
}
if (endExclude > strLength) {
endExclude = strLength;
}
if (startInclude > endExclude) {
// 如果起始位置大于结束位置不替换
return originalStr;
}
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < startInclude; i++) {
stringBuilder.append(new String(strCodePoints, i, 1));
}
stringBuilder.append(replacedStr);
for (int i = endExclude; i < strLength; i++) {
stringBuilder.append(new String(strCodePoints, i, 1));
}
return stringBuilder.toString();
}
/**
* 替换所有正则匹配的文本并使用自定义函数决定如何替换<br>
* replaceFun可以通过{@link Matcher}提取出匹配到的内容的不同部分然后经过重新处理组装变成新的内容放回原位

View File

@ -22,6 +22,13 @@ public class CharSequenceUtilTest {
Assert.assertEquals(replace, result);
}
@Test
public void replaceByStrTest(){
String replace = "SSM15930297701BeryAllen";
String result = CharSequenceUtil.replace(replace, 5, 12, "***");
Assert.assertEquals("SSM15***01BeryAllen", result);
}
@Test
public void addPrefixIfNotTest(){
String str = "hutool";

View File

@ -2,6 +2,7 @@ package cn.hutool.core.text.csv;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import org.junit.Ignore;
import org.junit.Test;
public class CsvWriterTest {