Java 中 equals() 与 equalsIgnoreCase() 的区别
在 Java 中使用 equals() 检查两个字符串是否相等。
在 Java 中使用 equalsIgnoreCase() 检查两个字符串是否相等,而不考虑大小写。
假设以下为我们两个字符串 −
String one = "qwerty"; String two = "Qwerty";
两者相等,但大小写不同。由于该方法忽略大小写,使用 equalsIgnoreCase() 方法将这两个字符串视为相等。
在此,我们检查同样的内容 −
if(one.equalsIgnoreCase(two)) { System.out.println("String one is equal to two (ignoring the case) i.e. one==two"); }else{ System.out.println("String one is not equal to String two (ignoring the case) i.e. one!=two"); }
然而,在 equals() 大小写情况下,它们不会被视为相等 −
if(one.equals(two)) { System.out.println("String one is equal to two i.e. one==two"); }else{ System.out.println("String one is not equal to String two i.e. one!=two"); }
以下是最后一个示例。
示例
public class Demo { public static void main(String[] args) { String one = "qwerty"; String two = "Qwerty"; if(one.equalsIgnoreCase(two)) { System.out.println("String one is equal to two (ignoring the case) i.e. one==two"); }else{ System.out.println("String one is not equal to String two (ignoring the case) i.e. one!=two"); } if(one.equals(two)) { System.out.println("String one is equal to two i.e. one==two"); }else{ System.out.println("String one is not equal to String two i.e. one!=two"); } } }
输出
String one is equal to two (ignoring the case) i.e. one==two String one is not equal to String two i.e. one!=two
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP