Comparing Strings in Java – 在Java中比较字符串

最后修改: 2018年 2月 24日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll talk about the different ways of comparing Strings in Java.

在这篇文章中,我们将讨论Java中比较字符串的不同方法。

As String is one of the most used data types in Java, this is naturally a very commonly used operation.

由于String是Java中使用最多的数据类型之一,这自然是一个非常常用的操作。

2. String Comparison With String Class

2.StringString类的比较

2.1. Using “==” Comparison Operator

2.1.使用“==”比较运算符

Using the “==” operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because “==” only checks the referential equality of two Strings, meaning if they reference the same object or not.

使用”==”运算符来比较文本值是Java初学者最常犯的错误之一。这是不正确的,因为“==”只检查两个字符串的引用是否相等,意思是它们是否引用同一个对象。

Let’s see an example of this behavior:

让我们看看这种行为的一个例子。

String string1 = "using comparison operator";
String string2 = "using comparison operator";
String string3 = new String("using comparison operator");
 
assertThat(string1 == string2).isTrue();
assertThat(string1 == string3).isFalse();

In the example above, the first assertion is true because the two variables point to the same String literal.

在上面的例子中,第一个断言是真的,因为这两个变量指向同一个String字面。

On the other hand, the second assertion is false because string1 is created with a literal and string3 is created using the new operator – therefore they reference different objects.

另一方面,第二个断言是错误的,因为string1是用一个字面创建的,而string3是用new操作符创建的–因此它们引用了不同的对象。

2.2. Using equals()

2.2.使用equals()

The String class overrides the equals() inherited from Object. This method compares two Strings character by character, ignoring their address.

String类重写了继承自Object的equals()该方法对两个字符串逐个字符进行比较,忽略它们的地址。

It considers them equal if they are of the same length and the characters are in same order:

如果它们的长度相同,而且字符的顺序相同,它就认为它们是相等的。

String string1 = "using equals method";
String string2 = "using equals method";
        
String string3 = "using EQUALS method";
String string4 = new String("using equals method");

assertThat(string1.equals(string2)).isTrue();
assertThat(string1.equals(string4)).isTrue();

assertThat(string1.equals(null)).isFalse();
assertThat(string1.equals(string3)).isFalse();

In this example, string1, string2, and string4 variables are equal because they have the same case and value irrespective of their address.

在这个例子中,string1, string2,string4变量是相等的,因为它们具有相同的大小写和值,而不考虑其地址。

For string3 the method returns false, as it’s case sensitive.

对于string3,该方法返回false,,因为它是区分大小写的。

Also, if any of the two strings is null, then the method returns false.

此外,如果两个字符串中的任何一个是null,那么该方法返回false.

2.3. Using equalsIgnoreCase()

2.3.使用equalsIgnoreCase()

The equalsIgnoreCase() method returns a boolean value. As the name suggests this method ignores casing in characters while comparing Strings:

equalsIgnoreCase()方法返回一个布尔值。顾名思义,这个方法在比较字符串时忽略字符的大小写:

String string1 = "using equals ignore case";
String string2 = "USING EQUALS IGNORE CASE";

assertThat(string1.equalsIgnoreCase(string2)).isTrue();

2.4. Using compareTo()

2.4.使用compareTo()

The compareTo() method returns an int type value and compares two Strings character by character lexicographically based on a dictionary or natural ordering.

compareTo()方法返回一个int类型的值,根据字典或自然排序,逐个字符比较两个Strings字符

This method returns 0 if two Strings are equal, a negative number if the first String comes before the argument, and a number greater than zero if the first String comes after the argument String.

如果两个字符串相等,该方法返回0;如果第一个字符串在参数之前,则返回一个负数;如果第一个字符串在参数字符串之后,则返回一个大于零的数字。

Let’s see an example:

让我们看一个例子。

String author = "author";
String book = "book";
String duplicateBook = "book";

assertThat(author.compareTo(book))
  .isEqualTo(-1);
assertThat(book.compareTo(author))
  .isEqualTo(1);
assertThat(duplicateBook.compareTo(book))
  .isEqualTo(0);

2.5. Using compareToIgnoreCase()

2.5.使用compareToIgnoreCase()

The compareToIgnoreCase() is similar to the previous method, except it ignores case:

compareToIgnoreCase()与前一个方法类似,只是它忽略了大小写。

String author = "Author";
String book = "book";
String duplicateBook = "BOOK";

assertThat(author.compareToIgnoreCase(book))
  .isEqualTo(-1);
assertThat(book.compareToIgnoreCase(author))
  .isEqualTo(1);
assertThat(duplicateBook.compareToIgnoreCase(book))
  .isEqualTo(0);

3. String Comparison With Objects Class

3.StringObjects类的比较

Objects is a utility class which contains a static equals() method, useful in this scenario – to compare two Strings.

Objects是一个实用类,包含一个静态的equals()方法,在这种情况下很有用–比较两个字符串。

The method returns true if two Strings are equal by first comparing them using their address i.e “==”. Consequently, if both arguments are null, it returns true and if exactly one argument is null, it returns false.

如果两个字符串相等,该方法会返回true,因为首先用它们的地址进行比较即”==”。因此,如果两个参数都是null,它返回true,如果正好有一个参数是null,它返回false。

Otherwise, it then simply calls the equals() method of the passed argument’s type’s class – which in our case is String’s class equals() method. This method is case sensitive because it internally calls String class’s equals() method.

否则,它就会简单地调用所传参数类型的equals()方法–在我们的例子中是String类的equals()方法。这个方法是区分大小写的,因为它在内部调用String类的equals()方法。

Let’s test this:

让我们来测试一下。

String string1 = "using objects equals";
String string2 = "using objects equals";
String string3 = new String("using objects equals");

assertThat(Objects.equals(string1, string2)).isTrue();
assertThat(Objects.equals(string1, string3)).isTrue();

assertThat(Objects.equals(null, null)).isTrue();
assertThat(Objects.equals(null, string1)).isFalse();

4. String Comparison With Apache Commons

4.字符串Apache Commons的比较

The Apache Commons library contains a utility class called StringUtils for String-related operations; this also has some very beneficial methods for String comparison.

Apache Commons库包含一个名为StringUtils的实用类,用于String-相关的操作;这也有一些对String比较非常有益的方法。

4.1. Using equals() and equalsIgnoreCase()

4.1.使用equals()/em>和equalsIgnoreCase()

The equals() method of StringUtils class is an enhanced version of the String class method equals(), which also handles null values:

StringUtils类的equals()方法是String类方法equals()的增强版,它也处理空值。

assertThat(StringUtils.equals(null, null))
  .isTrue();
assertThat(StringUtils.equals(null, "equals method"))
  .isFalse();
assertThat(StringUtils.equals("equals method", "equals method"))
  .isTrue();
assertThat(StringUtils.equals("equals method", "EQUALS METHOD"))
  .isFalse();

The equalsIgnoreCase() method of StringUtils returns a boolean value. This works similarly to equals(), except it ignores casing of characters in Strings:

StringUtilsequalsIgnoreCase()方法返回一个boolean值。它的工作原理与equals()相似,但它忽略了字符串中字符的大小写:

assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method"))
  .isTrue();
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD"))
  .isTrue();

4.2. Using equalsAny() and equalsAnyIgnoreCase()

4.2.使用equalsAny()/em>和equalsAnyIgnoreCase()/em>

The equalsAny() method’s first argument is a String and the second is a multi-args type CharSequence. The method returns true if any of the other given Strings match against the first String case sensitively.

equalsAny()方法的第一个参数是一个String,第二个参数是一个多args类型CharSequence。如果任何其他给定的字符串与第一个字符串敏感地匹配,该方法返回

Otherwise, false is returned:

否则,将返回false。

assertThat(StringUtils.equalsAny(null, null, null))
  .isTrue();
assertThat(StringUtils.equalsAny("equals any", "equals any", "any"))
  .isTrue();
assertThat(StringUtils.equalsAny("equals any", null, "equals any"))
  .isTrue();
assertThat(StringUtils.equalsAny(null, "equals", "any"))
  .isFalse();
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY"))
  .isFalse();

The equalsAnyIgnoreCase() method works similarly to the equalsAny() method, but also ignores casing:

equalsAnyIgnoreCase()方法的工作原理与equalsAny()方法相似,但也忽略了大小写。

assertThat(StringUtils.equalsAnyIgnoreCase("ignore case", "IGNORE CASE", "any")).isTrue();

4.3. Using compare() and compareIgnoreCase()

4.3.使用compare()/em>和compareIgnoreCase()

The compare() method in StringUtils class is a null-safe version of the compareTo() method of String class and handles null values by considering a null value less than a non-null value. Two null values are considered equal.

StringUtils类中的compare()方法是String类中的compareTo()方法的空安全版本,通过考虑null值小于non-null值来处理null两个null值被视为相等。

Furthermore, this method can be used to sort a list of Strings with null entries:

此外,该方法可用于对包含null项的字符串列表进行排序。

assertThat(StringUtils.compare(null, null))
  .isEqualTo(0);
assertThat(StringUtils.compare(null, "abc"))
  .isEqualTo(-1);
assertThat(StringUtils.compare("abc", "bbc"))
  .isEqualTo(-1);
assertThat(StringUtils.compare("bbc", "abc"))
  .isEqualTo(1);

The compareIgnoreCase() method behaves similarly, except it ignores casing:

compareIgnoreCase()方法的行为与此类似,只是它忽略了大小写。

assertThat(StringUtils.compareIgnoreCase("Abc", "bbc"))
  .isEqualTo(-1);
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC"))
  .isEqualTo(1);
assertThat(StringUtils.compareIgnoreCase("abc", "ABC"))
  .isEqualTo(0);

The two methods can also be used with a nullIsLess option. This is a third boolean argument which decides if null values should be considered less or not.

这两个方法也可以与nullIsLess选项一起使用。这是第三个boolean参数,它决定空值是否应该被认为是少的

A null value is lower than another String if nullIsLess is true and higher if nullIsLess is false.

如果nullIsLess为真,则null值低于另一个String,如果nullIsLess为假,则null值高于另一个String

Let’s try it out:

让我们来试一试。

assertThat(StringUtils.compare(null, "abc", true))
  .isEqualTo(-1);
assertThat(StringUtils.compare(null, "abc", false))
  .isEqualTo(1);

The compareIgnoreCase() method with a third boolean argument work similarly, except by ignoring case.

带有第三个boolean参数的compareIgnoreCase()方法工作类似,只是忽略了大小写。

5. Conclusion

5.结论

In this quick tutorial, we discussed different ways of comparing Strings.

在这个快速教程中,我们讨论了比较字符串的不同方法。

And, as always, the source code for the examples can be found over on GitHub.

而且,像往常一样,这些例子的源代码可以在GitHub上找到