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