0

可能重复:
如何比较 Java 中的字符串?

我写了一些比较两个字符串“abc”和“de”的代码。字符串 abc 被解析并返回“doc”到 ext,然后进行比较。尽管似乎 if 条件为真,但 else 部分仍在执行。我没有得到请帮助我....非常感谢。

public class xyz{

    String abc="doc2.doc";
    String de="doc";

    public static void main(String arg[]){

    xyz c=new xyz();

    String ext = null;
    String s =c.abc;
        String d =c.de;
    int i = s.lastIndexOf('.');

    if (i > 0 && i < s.length() - 1){
    ext = s.substring(i+1).toLowerCase();
    }
    System.out.println(ext);
    if(ext==d){

    System.out.println("true");
    }
    else{
    System.out.println("false");
    }


    }


    }
4

7 回答 7

3

您不能将字符串与==运算符进行比较。

你将不得不使用String.equals()

在你的情况下,它会是

if (ext.equals(d)) {
    System.out.println("true");
} else {
    System.out.println("false");
}
于 2012-10-03T10:52:35.167 回答
1

==测试参考相等。

.equals()测试值相等。

因此,如果你真的想测试两个字符串是否具有相同的值,你应该使用 .equals()

// These two have the same value
new String("test").equals("test") ==> true 

// ... but they are not the same object
new String("test") == "test" ==> false 

// ... neither are these
new String("test") == new String("test") ==> false 

在这种情况下

if(ext.equals(d)) {
    System.out.println("true");
}
else {
    System.out.println("false");
}
于 2012-10-03T10:53:43.823 回答
0

使用equals运算符比较字符串:

ext.equals(d)
于 2012-10-03T10:54:41.633 回答
0

你可以用 .equals()..

private String a = "lol";

public boolean isEqual(String test){
  return this.a.equals(test);
}
于 2012-10-03T10:56:25.420 回答
0

您不能将字符串与 == 进行比较,因为它们是不同的对象。内容可能相同,但这不是 == 所看到的。对其中一个字符串使用 equals 方法将其与另一个字符串进行比较。

在您的代码中,使用:

if(d.equals(ext)){

如果您需要比较两个字符串,而其中只有一个是变量,我建议采用以下方法:

"foo".equals(variableString)

这样您就可以确定不会在 Null 对象上调用 equals。

另一种可能性是使用 compareTo 方法而不是在其他一些 Java 类中也可以找到的 equals 方法。当字符串匹配时 compareTo 方法返回 0。

您可以在此处找到有关 Java 中字符串的更多信息。

于 2012-10-03T10:59:27.257 回答
0

你应该写

if(ext.equals(d))

instead of 

if(ext==d)
于 2012-10-03T11:02:22.500 回答
0
String str1, str2, str; // References to instances of String or null

str1 = "hello"; // The reference str1 points to an instance of "hello" string
str2 = "hello"; // The reference str2 points to another instance of "hello" string
str3 = str2;    // The reference str3 points to the same instance which str2 does.

assert str1.equals( str2 ); // Both string instances are identical.
assert str1 != str2;        // Both references point to independent instances of string.
assert str2 == str3;        // Both references point to the same instance of string.
于 2012-10-03T11:17:35.313 回答