Java String类中CaseInsensitiveComparator.compare()方法的实现
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 promotion 16 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 should 23 // 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 properly 30 // for the Georgian alphabet, which has strange rules about case 31 // conversion. So we need to make one last check before 32 // exiting. 33 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { 34 continue; 35 } 36 } 37 return false; 38 } 39 return true; 40 }
全文完。
\n
重剑无锋,大巧不工。