如题,上网找了一圈发现都是用JavaScript实现的,只好自己将JavaScript实现的代码转为Java代码实现:
// String -> 零宽字符
public static String strToZeroWidth(String str){
String collect = Arrays.stream(str.split(""))
.map(item -> Integer.toBinaryString(item.charAt(0)))
.collect(Collectors.joining(" "));
String result = Arrays.stream(collect.split(""))
.map(item -> {
if (item.equals("1")) {
return "\u200B";
} else if (item.equals("0")) {
return "\u200C";
} else {
return "\u200D";
}
})
.collect(Collectors.joining(""));
return result;
}
// 零宽字符 -> String
public static String zeroWidthToStr(String str){
//去除非零宽字符,只对零宽字符进行转换
String lkzf = str.replaceAll("[^\u200b-\u200f\uFEFF\u202a-\u202e]", "");
String collect = Arrays.stream(lkzf.split(""))
.map(item -> {
if ("\u200B".equals(item)) {
return "1";
} else if ("\u200C".equals(item)) {
return "0";
} else {
return " ";
}
})
.collect(Collectors.joining(""));
String result = Arrays.stream(collect.split(" "))
.map(item -> "" + (char) Integer.parseInt(item, 2))
.collect(Collectors.joining(""));
return result;
}
// 测试
public static void main(String[] args) {
String lkzf = strToZeroWidth("中间");
System.out.println("lkzf = " + lkzf);
String result1 = "零宽" + lkzf + "字符";
System.out.println(result1);
System.out.println(result1.length());
String result2 = zeroWidthToStr(result1);
System.out.println("result2 = " + result2);
}
输出:
![image-20230116233514769](/i/l/?n=23&i=blog/2029892/202301/2029892-20230116233601634-485422692.png)
lkzf =
零宽字符
36
result2 = 中间
标签:字符,return,String,collect,lkzf,item,字符串,Java
From: https://www.cnblogs.com/harglo/p/17056731.html