我们可以通过各种方式比较Java中的字符串-
使用comapareTo()
方法-的的compareTo()方法两个字符串按字典顺序进行比较。比较是基于字符串中每个字符的Unicode值。在字典上比较此String对象表示的字符序列与自变量字符串表示的字符序列。
import java.util.Scanner; public class StringComparison { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter string1: "); String str1 = sc.next(); System.out.println("Enter string2: "); String str2 = sc.next(); int result = str1.compareTo(str2); if (result < 0) { System.out.println("str1 is not equal to str2"); } else if (result == 0) { System.out.println("str1 is equal to str2"); } else { System.out.println("str1 is not equal to str2"); } } }
Enter string1: Hello Enter string2: Hello str1 is equal to str2
Enter string1: hello Enter string2: hi str1 is not equal to str2
使用==运算符-您可以使用==运算符比较两个字符串。但是,它比较给定变量的引用而不是值。
import java.util.Scanner; public class StringComparison { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str1 = "hello"; String str2 = "hello"; if (str1 == str2 ){ System.out.println("Both are equal"); } else { System.out.println("Both are not equal"); } } }
Both are equal
使用String类的equals()方法-接受String作为参数,并将当前字符串与指定对象进行比较。当且仅当参数不为null,并且是一个String对象,表示与此对象相同的字符序列(包括大小写),结果为true。
import java.util.Scanner; public class StringComparison { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter string1: "); String str1 = sc.next(); System.out.println("Enter string2: "); String str2 = sc.next(); boolean bool = str1.equals(str2); if (bool) { System.out.println("Both are equal"); } else { System.out.println("Both are not equal"); } } }
Enter string1: Hello Enter string2: hello Both are not equal
Enter string1: Hello Enter string2: Hello Both are equal
String类的equalsIgnoreCase()方法与该equals()
方法类似,不同之处在于此方法将给定的字符串与当前的一个忽略大小写的字符串进行比较。
import java.util.Scanner; public class StringComparison { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter string1: "); String str1 = sc.next(); System.out.println("Enter string2: "); String str2 = sc.next(); boolean bool = str1.equalsIgnoreCase(str2); if (bool) { System.out.println("Both are equal"); } else { System.out.println("Both are not equal"); } } }
Enter string1: Hello Enter string2: hello Both are equal