【问题标题】:Issue with String unicode字符串 unicode 的问题
【发布时间】:2015-02-03 09:26:57
【问题描述】:

我在比较两个字符串时遇到问题。它总是导致错误。我认为空间的 unicode 存在问题。

String actual =   "cars in";
String expected = "cars in";
for(int i=0;i<expected.length();i++){
        System.out.print(expected.codePointAt(i)+" ");
        System.out.print(actual.codePointAt(i)+" ");
        System.out.println();
    }
if(actual.equals(expected)){
        System.out.println(true);
    }else
        System.out.println(false);

我也尝试打印 codePoint,结果如下。

99 99 
97 97 
114 114 
115 115 
32 160 
105 105 
110 110 

所以空间的值不同,在第一个字符串中,值为32,在第二个字符串中,值为160,因此每次比较两者时它都会给出错误。

我该如何解决这个问题?

【问题讨论】:

  • '160' 是一个不间断空格,而 32 只是一个空格 en.wikipedia.org/wiki/Non-breaking_space
  • 那么如何比较我得到真实结果的字符串。
  • 您可以使用String replace() 将不间断空格转换为普通空格
  • 谢谢@DmitryBychenko,我明白了! :)

标签: java string unicode


【解决方案1】:

你可以尝试根据空格分割字符串-:

String actual = "cars in";
String expected = "cars in";
String[] str1 = actual.split(" ");
String[] str2 = expected.split(" ");
for (int i = 0; i < str1.length; i++) {
    if (str1[i].equals(str2[i])) {
        System.out.println(true);
    }
}

【讨论】:

  • 这可能已经改变了,因为我在这里复制粘贴了代码。在我的机器中,输出与我给出的相同。
  • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。您可以随时edit您的帖子将其更改为实际答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 2011-10-11
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
相关资源
最近更新 更多