如何在Java中进行不区分大小写的字符串比较?
我们可以通过多种方式在Java中比较字符串:
使用compareTo()方法 − **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"); } } }
输出1
Enter string1: Hello Enter string2: Hello str1 is equal to str2
输出2
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
使用**equals()** 方法 − String类的**equals()**方法接受一个String作为参数,并将当前字符串与指定的Object进行比较。当且仅当参数不为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"); } } }
输出1
Enter string1: Hello Enter string2: hello Both are not equal
输出2
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"); } } }
输出1
Enter string1: Hello Enter string2: hello Both are equal
广告