字符串比较无法正常工作

时间:2014-09-09 14:37:19

标签: java string comparison equals

我在使用字符串比较时出现问题,而有些字会返回正确的结果,其他字母只是不会...

for (int s = 0; s < subjects.getLength(); s++) {
    Element subject = (Element) subjects.item(s);
    String sub = subject
                    .getElementsByTagName("name").item(0)
                    .getTextContent();
    Log.d("Subject", getSubject() + "!A");
    Log.d("Subject", sub + "!B");
    Log.d("Subject", "equalsIC: " + String.valueOf(getSubject().equalsIgnoreCase(sub)));
    Log.d("Subject", "Contains: " + String.valueOf(getSubject().contains(sub)));
    Log.d("Subject", "Equals: " + String.valueOf(getSubject().equals(sub)));
    Log.d("Subject", "ContentEqu: " + String.valueOf(getSubject().contentEquals(sub)));
    Log.d("Subject", "Length A: " + String.valueOf(getSubject().length()) + "; Length B: " + String.valueOf(sub.length()));
    if (getSubject().equalsIgnoreCase(subject
               .getElementsByTagName("name").item(0)
               .getTextContent())) {
        Log.d("Subject", getSubject() + "Success !C");

getSubject方法返回一个String。 虽然这适用于&#34; BK G3&#34;:

D/Subject﹕ BK G3!A
D/Subject﹕ BK G3!B
D/Subject﹕ equalsIC: true
D/Subject﹕ Contains: true
D/Subject﹕ Equals: true
D/Subject﹕ ContentEqu: true
D/Subject﹕ Length A: 5; Length B: 5
D/Subject﹕ BK G3Success !C

它完全失败了&#34; D G4&#34;:

D/Subject﹕ D  G4!A
D/Subject﹕ D  G4!B
D/Subject﹕ equalsIC: false
D/Subject﹕ Contains: false
D/Subject﹕ Equals: false
D/Subject﹕ ContentEqu: false
D/Subject﹕ Length A: 5; Length B: 5

我用sub.trim()尝试过,但没有改变..

提前致谢。

修改

调试为我提供了以下信息:

sub = (java.lang.String@83000929)"D  G4"
value = {char[5]@830092913560}
hashCode = 0
offset = 0
count = 5

((Activity_Add)this).subject = java.lang.String@830088265176)"D  G4"
value = {char[59]@830080636976}
hashCode = 0
offset = 6
count = 5

1 个答案:

答案 0 :(得分:0)

使用

sub.replaceAll("\\s+","")

而不是

sub.trim();