Java String类提供了不同的比较方法,即:
compareTo()
方法此方法按字典顺序比较两个字符串。如果当前String对象在字典上在参数字符串之前,则此方法返回一个负整数。一个正整数,如果当前的String对象在字典上遵循该参数当字符串相等时为true。
import java.lang.*; public class StringDemo { public static void main(String[] args) { String str1 = "tutorials", str2 = "point"; //比较str1和str2- int retval = str1.compareTo(str2); //打印比较的返回值 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"; //比较str1和str2- with case ignored int retval = str1.compareToIgnoreCase(str2); //打印比较的返回值 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并且是一个String对象,表示与此对象相同的字符序列时,结果为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"; //检查是否相等 boolean retval1 = str2.equals(str1); boolean retval2 = str2.equals(str3); //打印返回值 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"; //检查是否相等 with case ignored boolean retval1 = str2.equalsIgnoreCase(str1); boolean retval2 = str2.equalsIgnoreCase(str3); //打印返回值 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