优雅的方式来检查两个字符串是否不同

时间:2013-06-11 08:31:29

标签: c# java string-comparison

是否有一种优雅的方式来比较两个Strings并检查它们是否不同?例如,在Java中,我通常使用与此类似的东西:

if (text1 != text2 || (text1 != null && !text1.equals(text2))) {
    // Texts are different
}

这是非常普遍的事情,我想知道可能有更好的方法。

修改 理想情况下,我想要一个适用于大多数常见面向对象语言的伪代码。

4 个答案:

答案 0 :(得分:10)

在Java 7+中,您可以使用Objects#equals

if (!Objects.equals(text1, text2))

在幕后,它的功能类似于你问题中的代码:

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

请注意,您的代码在Java中被破坏:在这种情况下它将返回false:

String text1 = "abc";
String text2 = new String("abc");
if (text1 != text2 || (text1 != null && !text1.equals(text2))) {
    System.out.println("Ooops, there is a bug");
}

编写isNotEquals条件的正确方法是:

if (text1 != text2 && (text1 == null || !text1.equals(text2)))

答案 1 :(得分:3)

这(C#):

if(text1 != text2){
}

应该这样做,因为==运算符和!=运算符被重载以进行正确的字符串比较。

MSDN Reference

答案 2 :(得分:3)

Java(7开始):

Objects.equals(first, second);

C#:

string.Equals(first, second);

答案 3 :(得分:0)

在c#个人中我使用上面的

If(!string.IsNullOrEmpty(text1) || (!string.IsNullOrEmpty(text2) && (text1 != text2 )))
 {}
相关问题