Java不可见字符处理
逛博客园的时候,看到一篇文章,比较两个字符串是否相等,比较两个字符串,用了一个晚上.
string m1 = "fac5046bc10aca2e1ea955ebe4537dc0";
string m2 = "fac5046bc10aca2e1ea955ebe4537dc0";
是不相等的。因为m1里面含有不可见字符(zero-width non-joiner (ZWNJ),zero-width space (ZWSP) 这两种)
解决办法:
①.复制到QQ里,就可以看到区别了。
②.用Java代码来区别
1 String m1 = "fac5046bc10aca2e1ea955ebe4537dc0"; 2 String m2 = "fac5046bc10aca2e1ea955ebe4537dc0"; 3 System.out.println("m1的长度:"+m1.length() + "\n" +"m2的长度:" + m2.length()); 4 byte[] bs = m1.getBytes(); 5 System.out.print("m1:"); 6 for (byte b : bs) { 7 System.out.print(b + " "); 8 } 9 System.out.println(); 10 String all = m1.replaceAll("\\p{C}", ""); 11 System.out.println(m2.equals(all));
得到输出结果:
m1的长度:62 m2的长度:32 m1:102 97 -30 -128 -116 -30 -128 -117 99 53 -30 -128 -116 -30 -128 -117 48 52 -30 -128 -116 -30 -128 -117 54 98 -30 -128 -116 -30 -128 -117 99 49
-30 -128 -116 -30 -128 -117 48 97 -30 -128 -116 -30 -128 -117 99 97 -30 -128 -116 -30 -128 -117 50 101 -30 -128 -116 -30 -128 -117 49 101 -30 -128
-116 -30 -128 -117 97 57 -30 -128 -116 -30 -128 -117 53 53 -30 -128 -116 -30 -128 -117 101 98 -30 -128 -116 -30 -128 -117 101 52 -30 -128 -116 -30
-128 -117 53 51 -30 -128 -116 -30 -128 -117 55 100 -30 -128 -116 -30 -128 -117 99 48 true