Java 字符串对比方法。
Java 字符串类提供了不同的比较方法,即
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
广告