如何在 Java 中使用 equals() 和 equalsIgnoreCase()。
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP