实现说明
真正干活的是类 InvisibleCharCleaner和函数 main、stripFormat,其余都是接线。
使用要点
- 每一步打印都带着自己的标签:
isWhitespace(U+200B):、length before :、length after :。 main按顺序串起stripFormat;运行文件就会把这个流程跑一遍。
常见问题
运行「剔除零宽字符的文本清洗」会打印什么?
运行文件本身,isWhitespace(U+200B):、length before :、length after : 这些前缀各对应一段演示逻辑。
核心语句
return out.toString();
.filter(cp -> Character.getType(cp) != Character.FORMAT)
.forEach(out::appendCodePoint);
代码示例
public class InvisibleCharCleaner {
public static void main(String[] args) {
// U+200B ZERO WIDTH SPACE 与 U+FEFF BOM:肉眼不可见,却计入长度
String pasted = "pay\u200Bload\uFEFF";
// trim/strip 只认 isWhitespace:零宽字符不属于空白,原样保留
System.out.println("isWhitespace(U+200B): " + Character.isWhitespace('\u200B'));
System.out.println("length before : " + pasted.length());
String cleaned = stripFormat(pasted);
System.out.println("length after : " + cleaned.length());
System.out.println("cleaned : [" + cleaned + "]");
}
// 按通用类别过滤:FORMAT(Cf)承载零宽字符与 BOM
static String stripFormat(String text) {
StringBuilder out = new StringBuilder(text.length());
text.codePoints()
.filter(cp -> Character.getType(cp) != Character.FORMAT)
.forEach(out::appendCodePoint);
return out.toString();
}
}