標籤:
String對象的大小寫不敏感比較方法的實現如下:
1 public int compare(String s1, String s2) { 2 int n1 = s1.length(); 3 int n2 = s2.length(); 4 int min = Math.min(n1, n2); 5 for (int i = 0; i < min; i++) { 6 char c1 = s1.charAt(i); 7 char c2 = s2.charAt(i); 8 if (c1 != c2) { 9 c1 = Character.toUpperCase(c1);10 c2 = Character.toUpperCase(c2);11 if (c1 != c2) {12 c1 = Character.toLowerCase(c1);13 c2 = Character.toLowerCase(c2);14 if (c1 != c2) {15 // No overflow because of numeric promotion16 return c1 - c2;17 }18 }19 }20 }21 return n1 - n2;22 }
這裡,同時比較了UpperCase和LowerCase,是為了相容Georgian字元。
見String類的regionMatches()方法。如下(29~32行):
1 public boolean regionMatches(boolean ignoreCase, int toffset, 2 String other, int ooffset, int len) { 3 char ta[] = value; 4 int to = toffset; 5 char pa[] = other.value; 6 int po = ooffset; 7 // Note: toffset, ooffset, or len might be near -1>>>1. 8 if ((ooffset < 0) || (toffset < 0) 9 || (toffset > (long)value.length - len)10 || (ooffset > (long)other.value.length - len)) {11 return false;12 }13 while (len-- > 0) {14 char c1 = ta[to++];15 char c2 = pa[po++];16 if (c1 == c2) {17 continue;18 }19 if (ignoreCase) {20 // If characters don‘t match but case may be ignored,21 // try converting both characters to uppercase.22 // If the results match, then the comparison scan should23 // continue.24 char u1 = Character.toUpperCase(c1);25 char u2 = Character.toUpperCase(c2);26 if (u1 == u2) {27 continue;28 }29 // Unfortunately, conversion to uppercase does not work properly30 // for the Georgian alphabet, which has strange rules about case31 // conversion. So we need to make one last check before32 // exiting.33 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {34 continue;35 }36 }37 return false;38 }39 return true;40 }
Java String類中CaseInsensitiveComparator.compare()方法的實現