Java字符串比较

Java String compare means checking lexicographically which string comes first. Sometimes it’s required to compare two strings so that a collection of strings can be sorted. For example, sorting students name so that it can be published in order and look good.

Java字符串比较意味着按字典顺序检查哪个字符串先出现。 有时需要比较两个字符串,以便可以对字符串集合进行排序。 例如,对学生姓名进行排序,以便可以按顺序将其发布并看起来不错。

Java字符串比较 (Java String Compare)

java string compare

There are five ways to compare two strings.


比较两种字符串有五种方法。

  1. Using == operator

    使用==运算符
  2. Using equals() method

    使用equals()方法
  3. Using compareTo() method

    使用compareTo()方法
  4. Using compareToIgnoreCase() method

    使用compareToIgnoreCase()方法
  5. Using java.text.Collator compare() method

    使用java.text.Collator compare()方法

Let’s look into each of these string comparison ways in detail.

让我们详细研究每种字符串比较方法。

使用==运算符的Java字符串比较 (Java String Comparison using == operator)

When double equals operator is used to compare two objects, it returns true when they are referring to the same object, otherwise false. Let’s look at some code snippets for using == for string comparison in java.

当使用double equals运算符比较两个对象时,当它们引用同一对象时,它返回true ,否则返回false 。 让我们看一些使用==在Java中进行字符串比较的代码片段。

String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //false
s3 = s3.intern();
System.out.println(s1 == s3); //true

As we know that when string literal is creating using double quotes, they go into String Pool. So s1 and s2 are actually referring to the same object in string pool, hence s1==s2 will return true.

我们知道,当使用双引号创建字符串文字时,它们将进入String Pool 。 因此s1和s2实际上是在字符串池中引用同一对象,因此s1==s2将返回true

When string is creating using new operator, it gets created in the heap space. So s1 and s2 are referring to different objects and hence s1==s3 will return false.

使用new运算符创建字符串时,将在堆空间中创建它。 因此s1和s2指的是不同的对象,因此s1==s3将返回false

Next, when we are calling intern() method on s3, it returns the reference with same value from string pool. Since we already have “abc” in the string pool, s3 also gets the same reference. So finally s1==s3 will return true.

接下来,当我们在s3上调用intern()方法时,它将从字符串池中返回具有相同值的引用。 由于字符串池中已经有“ abc”,因此s3也获得相同的引用。 所以最终s1==s3将返回true

Java字符串比较使用equals()方法 (Java String Compare using equals() method)

Note that String is immutable class, so it doesn’t make sense to compare them with == operator. When we are trying to compare the values of two string to be equal or not, better to use equals() method. If you are want to check for equality with case insensitivity, then you can use equalsIgnoreCase() method. Below code snippet shows examples of string comparison using equals() and equalsIgnoreCase() method.

请注意, String是不可变的类,因此将它们与==运算符进行比较没有任何意义。 当我们尝试比较两个字符串的值是否相等时,最好使用equals()方法。 如果要检查是否区分大小写是否相等,则可以使用equalsIgnoreCase()方法。 下面的代码片段显示了使用equals()equalsIgnoreCase()方法进行字符串比较的示例。

String s1 = "abc";
String s2 = "abc";
String s3 = new String("ABC");
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //false
System.out.println(s1.equalsIgnoreCase(s3)); //true

使用compareTo()方法的Java字符串比较 (Java String Comparison using compareTo() method)

Sometimes we don’t want to check for equality, we are interested in which string comes first lexicographically. This is important when we want to sort the collection of strings in order of appearance in the dictionary. Java String class implements Comparable interface and compareTo() method is used to compare string instance with another string.

有时我们不想检查是否相等,而是对按字典顺序排在最前面的字符串感兴趣。 当我们要按字典中出现的顺序对字符串集合进行排序时,这一点很重要。 Java String类实现Comparable接口,并且compareTo()方法用于将字符串实例与另一个字符串进行比较。

If this string precedes the argument passed, it returns negative integer otherwise positive integer. String compareTo() method returns 0 when both the strings are equal.

如果此字符串在传递的参数之前,则返回负整数,否则返回正整数。 当两个字符串相等时,字符串compareTo()方法将返回0。

The comparison is based on the Unicode value of each character in the strings. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. Assuming index ‘n’ is where characters are different then compareTo() will return this.charAt(n)-argumentString.charAt(n).

比较是基于字符串中每个字符的Unicode值。 如果两个字符串不同,那么它们要么在某个索引处具有不同的字符(这是两个字符串的有效索引),要么它们的长度不同,或者两者都有。 假设索引'n'是字符不同的地方,那么compareTo()将返回this.charAt(n)-argumentString.charAt(n)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo() method returns the difference of the lengths of the strings i.e. this.length()-argumentString.length().

如果在它们之间没有索引位置不同,则较短的字符串在字典上在较长的字符串之前。 在这种情况下,compareTo()方法返回字符串长度的差,即this.length()-argumentString.length()

Let’s look at some code snippets for java string compare using compareTo() method.

让我们看一下使用compareTo()方法进行Java字符串比较的一些代码片段。

String str = "ABC";
System.out.println(str.compareTo("DEF")); //-3 (Integer.valueOf('A') - Integer.valueOf('D'))
System.out.println(str.compareTo("ABC")); //0 (equal string)
System.out.println(str.compareTo("abc")); //-32 (Integer.valueOf('A') - Integer.valueOf('a'))
System.out.println(str.compareTo("AB")); //1 (difference in length)

Just go through the above code snippets, they are easy to understand based on the concept explained above.

只需阅读上面的代码片段,基于上面介绍的概念,它们就很容易理解。

使用compareToIgnoreCase()方法的Java字符串比较 (Java String Comparison using compareToIgnoreCase() method)

Java String compareToIgnoreCase() method is similar to compareTo() method, except that case is ignored. Let’s look at a simple example where we will compare two input strings provided by user.

Java字符串compareToIgnoreCase()方法与compareTo()方法类似,但会忽略这种情况。 让我们看一个简单的示例,在此示例中,我们将比较用户提供的两个输入字符串。

package com.journaldev.string;

import java.util.Scanner;

public class JavaStringCompare {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.println("Enter First String:");
		String first = sc.nextLine();
		System.out.println("Enter Second String:");
		String second = sc.nextLine();
		sc.close();

		System.out.println(first.compareTo(second));

		System.out.println(first.compareToIgnoreCase(second));

	}

}

Below image shows output of execution of above string comparison program.

下图显示了上述字符串比较程序的执行输出。

使用Collat​​or类的Java字符串比较 (Java String Comparison using Collator class)

For locale specific comparison, we should use java.text.Collator class. The most important feature of Collator is the ability to define our own custom comparison rules. Let’s look at a simple example of using Collator for string comparison.

对于特定于语言环境的比较,我们应该使用java.text.Collator类。 整理程序最重要的功能是能够定义我们自己的自定义比较规则。 让我们看一个使用Collat​​or进行字符串比较的简单示例。

package com.journaldev.string;

import java.text.Collator;
import java.text.ParseException;
import java.text.RuleBasedCollator;
import java.util.Locale;

public class JavaCollatorExample {

	public static void main(String[] args) throws ParseException {
		Collator collator = Collator.getInstance();
		Collator collatorFR = Collator.getInstance(Locale.FRANCE);

		System.out.println(collator.compare("X", "Z")); // -1
		System.out.println(collatorFR.compare("X", "Z")); // -1

		String rules = "< Z < X";
		RuleBasedCollator rbc = new RuleBasedCollator(rules);

		System.out.println(rbc.compare("X", "Z")); // 1
	}
}

Notice that "< Z < X" specifies a custom rule that Z comes before X apart from the natural ordering rule. That's why the output changed in the last comparison.

请注意, "< Z < X"指定了一个自定义规则,除了自然排序规则之外,Z在X之前。 这就是为什么输出在上一次比较中发生了变化。

That's all for different ways to compare two strings in java program.

这就是在Java程序中比较两个字符串的不同方式的全部。

References: Collator API Doc, String API Doc

参考: Collat​​or API DocString API Doc

翻译自: https://www.journaldev.com/18009/java-string-compare

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java字符串比较可以使用多种方法,其中最常用的是equals()方法。该方法比较两个字符串的内容是否相同,而不是比较它们的引用是否相同。因此,即使两个字符串对象的引用不同,只要它们的内容相同,equals()方法就会返回true。 以下是Java字符串比较的三种方法: 1.使用equals()方法比较字符串内容是否相同。 ```java String str1 = "hello"; String str2 = "world"; if(str1.equals(str2)){ System.out.println("str1和str2的内容相同");}else{ System.out.println("str1和str2的内容不同"); } ``` 2.使用compareTo()方法比较字符串的字典顺序。该方法返回一个整数,如果字符串在字典中排在参数字符串之前,则返回负数;如果字符串在字典中排在参数字符串之后,则返回正数;如果两个字符串相等,则返回0。 ```java String str1 = "hello"; String str2 = "world"; int result = str1.compareTo(str2); if(result < 0){ System.out.println("str1在字典中排在str2之前"); }else if(result > 0){ System.out.println("str1在字典中排在str2之后"); }else{ System.out.println("str1和str2在字典中的位置相同"); } ``` 3.使用==运算符比较两个字符串的引用是否相同。如果两个字符串的引用指向同一个对象,则返回true;否则返回false。 ```java String str1 = "hello"; String str2 = "hello"; if(str1 == str2){ System.out.println("str1和str2的引用相同"); }else{ System.out.println("str1和str2的引用不同"); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值