這裡不討論記憶體比對啥啥啥的問題,
單純的函式來比較.
equalsIgnoreCase
public boolean equalsIgnoreCase(String anotherString)
與anotherString比較字串是否相同,
equalsIgnoreCase會針對長度與每個字元比較, 比較3種情況
1. 利用 " == ", 比較字元
2. 利用 Character.toUpperCase(char) 判斷
3. 利用 Character.toLowerCase(char) 判斷
回傳: true 非null, 且以上判斷結果都相同; 否則回傳 false.
public class string_equalsIgnoreCase{
public static void main(String args[]){
String a = "abcdefg";
String b = "ABCDEFG";
String c = "AbCdEfG";
String d = "abc";
String e = "ABC";
String f = "AbC";
String g = "";
Output:
System.out.println(a.equalsIgnoreCase(a)); true
System.out.println(a.equalsIgnoreCase(b)); true
System.out.println(a.equalsIgnoreCase(c)); true
System.out.println(a.equalsIgnoreCase(d)); false
System.out.println(a.equalsIgnoreCase(e)); false
System.out.println(a.equalsIgnoreCase(f)); false
System.out.println(a.equalsIgnoreCase(g)); false
}
}
...以要改用SyntaxHighlighter來顯示 不然這樣看得好累
equals
public boolean equals(Object anObject)
與anObject比較字串是否相同,
回傳: true 非null, 且字串與anObject相同; 否則回傳 false.
public class string_equals{
public static void main(String args[]){
String a = "abcdefg";
String b = "ABCDEFG";
String c = "AbCdEfG";
String d = "abc";
String e = "ABC";
String f = "AbC";
String g = "";
Object y = "abcdefg";
Object z = "ABCDEFG";
Output:
System.out.println(a.equals(a)); true
System.out.println(a.equals(b)); false
System.out.println(a.equals(c)); false
System.out.println(a.equals(d)); false
System.out.println(a.equals(e)); false
System.out.println(a.equals(f)); false
System.out.println(a.equals(g)); false
System.out.println(a.equals(y)); true
System.out.println(a.equals(z)); false
}
}
compareTo
public int compareTo(String anotherString)
利用字典序 Lexicographic order 做排列,基本上就是利用String 裡面的每個字元的 Unicode value 做為比較依據.
如果字串比anotherString還要前面, 輸出就會出現負值.
如果字串比anotherString後面, 竟會出現正值.
如果字串都依樣, 就會出現 0.
其中出現0的前提是, compareTo會利用equals做前提比較, equals也回傳0.
其實字串比對還回牽扯到記憶體位置等等的, 那個懶得去想了. ㄎㄎ
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)
沒有留言:
張貼留言