feature: StrUtil增加替换字符串中第一个指定字符串和最后一个指定字符串方法

This commit is contained in:
herm2s 2022-08-15 17:50:11 +08:00
parent 2f66008d02
commit d6aa8fdb96
2 changed files with 76 additions and 0 deletions

View File

@ -3752,6 +3752,70 @@ public class CharSequenceUtil {
return ReUtil.replaceAll(str, regex, replaceFun); return ReUtil.replaceAll(str, regex, replaceFun);
} }
/**
* 替换字符串中最后一个指定字符串
*
* @param str 字符串
* @param searchStr 被查找的字符串
* @param replacedStr 被替换的字符串
* @return 替换后的字符串
*/
public static String replaceLast(CharSequence str, CharSequence searchStr, CharSequence replacedStr) {
return replaceLast(str, searchStr, replacedStr, false);
}
/**
* 替换字符串中最后一个指定字符串
*
* @param str 字符串
* @param searchStr 被查找的字符串
* @param replacedStr 被替换的字符串
* @param ignoreCase 是否忽略大小写
* @return 替换后的字符串
*/
public static String replaceLast(CharSequence str, CharSequence searchStr, CharSequence replacedStr, boolean ignoreCase) {
if (isEmpty(str)) {
return str(str);
}
int lastIndex = lastIndexOf(str, searchStr, str.length(), ignoreCase);
if (INDEX_NOT_FOUND == lastIndex) {
return str(str);
}
return replace(str, lastIndex, searchStr, replacedStr, ignoreCase);
}
/**
* 替换字符串中第一个指定字符串
*
* @param str 字符串
* @param searchStr 被查找的字符串
* @param replacedStr 被替换的字符串
* @return 替换后的字符串
*/
public static String replaceFirst(CharSequence str, CharSequence searchStr, CharSequence replacedStr) {
return replaceFirst(str, searchStr, replacedStr, false);
}
/**
* 替换字符串中第一个指定字符串
*
* @param str 字符串
* @param searchStr 被查找的字符串
* @param replacedStr 被替换的字符串
* @param ignoreCase 是否忽略大小写
* @return 替换后的字符串
*/
public static String replaceFirst(CharSequence str, CharSequence searchStr, CharSequence replacedStr, boolean ignoreCase) {
if (isEmpty(str)) {
return str(str);
}
int startInclude = indexOf(str, searchStr, 0, ignoreCase);
if (INDEX_NOT_FOUND == startInclude) {
return str(str);
}
return replace(str, startInclude, startInclude + searchStr.length(), replacedStr);
}
/** /**
* 替换指定字符串的指定区间内字符为"*" * 替换指定字符串的指定区间内字符为"*"
* 俗称脱敏功能后面其他功能可以见DesensitizedUtil(脱敏工具类) * 俗称脱敏功能后面其他功能可以见DesensitizedUtil(脱敏工具类)

View File

@ -618,5 +618,17 @@ public class StrUtilTest {
Assert.assertTrue(StrUtil.containsAll(a, "214", "234")); Assert.assertTrue(StrUtil.containsAll(a, "214", "234"));
} }
@Test
public void replaceLastTest() {
String str = "i am jackjack";
String result = StrUtil.replaceLast(str, "JACK", null, true);
Assert.assertEquals(result, "i am jack");
}
@Test
public void replaceFirstTest() {
String str = "yesyes i do";
String result = StrUtil.replaceFirst(str, "YES", "", true);
Assert.assertEquals(result, "yes i do");
}
} }