!149 增加过滤字符串的方法

Merge pull request !149 from 这个网名不错/v5-dev
This commit is contained in:
Looly 2020-08-01 22:25:02 +08:00 committed by Gitee
commit b3a0b023d3
2 changed files with 35 additions and 14 deletions

View File

@ -3,6 +3,7 @@ package cn.hutool.core.util;
import cn.hutool.core.comparator.VersionComparator;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.lang.Matcher;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.text.StrBuilder;
@ -1332,20 +1333,7 @@ public class StrUtil {
* @return 清理后的字符串
*/
public static String cleanBlank(CharSequence str) {
if (str == null) {
return null;
}
int len = str.length();
final StringBuilder sb = new StringBuilder(len);
char c;
for (int i = 0; i < len; i++) {
c = str.charAt(i);
if (false == CharUtil.isBlankChar(c)) {
sb.append(c);
}
}
return sb.toString();
return filter(str, c -> !CharUtil.isBlankChar(c));
}
// ------------------------------------------------------------------------------ Split
@ -4324,4 +4312,29 @@ public class StrUtil {
}
return new String(buffer);
}
/**
* 过滤字符串
*
* @param str 字符串
* @param filter 过滤器
* @return 过滤后的字符串
* @since 5.4.0
*/
public static String filter(CharSequence str, final Filter<Character> filter) {
if (str == null || filter == null) {
return str(str);
}
int len = str.length();
final StringBuilder sb = new StringBuilder(len);
char c;
for (int i = 0; i < len; i++) {
c = str.charAt(i);
if (filter.accept(c)) {
sb.append(c);
}
}
return sb.toString();
}
}

View File

@ -456,4 +456,12 @@ public class StrUtilTest {
String brief = StrUtil.brief(str, maxLength);
Assert.assertEquals(brief.length(), maxLength);
}
@Test
public void filterTest() {
final String filterNumber = StrUtil.filter("hutool678", CharUtil::isNumber);
Assert.assertEquals("678", filterNumber);
String cleanBlank = StrUtil.filter(" 你 好 ", c -> !CharUtil.isBlankChar(c));
Assert.assertEquals("你好", cleanBlank);
}
}