Java 字符串比较方法。


Java String 类提供了不同的比较方法,包括

compareTo() 方法

此方法按字典顺序比较两个字符串。此方法返回: 如果当前字符串对象按字典顺序在参数字符串前面,则返回值为负整数。 如果当前字符串对象按字典顺序在参数后面,则返回值为正整数。 如果字符串相等,则返回值为 true。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "point";
      // comparing str1 and str2
      int retval = str1.compareTo(str2);
      // prints the return value of the comparison
      if (retval < 0) {
         System.out.println("str1 is greater than str2");
      }
      else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}

输出

str1 is less than str2


compareToIgnoreCase() 方法

此方法与 compareTo() 方法相同,它按字典顺序比较两个字符串,忽略大小写差异。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "TUTORIALS";
     
      // comparing str1 and str2 with case ignored
      int retval = str1.compareToIgnoreCase(str2);
     
      // prints the return value of the comparison
      if (retval > 0) {
         System.out.println("str1 is greater than str2");
     }
     else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}

输出

str1 is equal to str2

equals() 方法

此方法将该字符串与指定对象进行比较。当且仅当参数不是 null 并且它表示与此对象相同字符序列的字符串对象时,结果才为 true。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "amrood admin";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

输出

str2 is equal to str1 = false
str2 is equal to str3 = true


equalsIgnoreCase() 方法 

此方法与 ignoreCase() 方法相同,但如果两个字符串长度相同,并且这两个字符串中的对应字符在忽略大小写的情况下相等,则认为这两个字符串是相等的。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "AMROOD ADMIN";
     
      // checking for equality with case ignored
      boolean retval1 = str2.equalsIgnoreCase(str1);
      boolean retval2 = str2.equalsIgnoreCase(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

输出

str2 is equal to str1 = false
str2 is equal to str3 = true

更新日期:2020 年 2 月 26 日

504 次浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.