publicbooleanregionMatches(boolean ignoreCase,int toffset,
String other,int ooffset,int len){char ta[]= value;int to = toffset;char pa[]= other.value;int po = ooffset;// Note: toffset, ooffset, or len might be near -1>>>1.if((ooffset <0)||(toffset <0)||(toffset >(long)value.length - len)||(ooffset >(long)other.value.length - len)){returnfalse;}while(len-->0){char c1 = ta[to++];char c2 = pa[po++];if(c1 == c2){continue;}if(ignoreCase){// If characters don't match but case may be ignored,// try converting both characters to uppercase.// If the results match, then the comparison scan should// continue.char u1 = Character.toUpperCase(c1);char u2 = Character.toUpperCase(c2);if(u1 == u2){continue;}// Unfortunately, conversion to uppercase does not work properly// for the Georgian alphabet, which has strange rules about case// conversion. So we need to make one last check before// exiting.if(Character.toLowerCase(u1)== Character.toLowerCase(u2)){continue;}}returnfalse;}returntrue;}
privatestaticclassCaseInsensitiveComparatorimplementsComparator<String>, java.io.Serializable {privatestaticfinallong serialVersionUID =8575799808933029326L;publicintcompare(String s1, String s2){int n1 = s1.length();int n2 = s2.length();int min = Math.min(n1, n2);for(int i =0; i < min; i++){char c1 = s1.charAt(i);char c2 = s2.charAt(i);if(c1 != c2){
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);if(c1 != c2){
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);if(c1 != c2){// No overflow because of numeric promotionreturn c1 - c2;}}}}return n1 - n2;}/** Replaces the de-serialized object. */private Object readResolve(){return CASE_INSENSITIVE_ORDER;}}
问题1:为什么不先判断两个字符串的长度?如果长度不相等,这两个字符串就不相等了呀
答案:未有
问题2:为什么需要转大写进行比较,还需要转小写进行比较?
答案:因为Georgian(格鲁吉亚)字母表,在转成大写之后不能正常工作,所以需要转大写后,再转为小写。详情见String类的public boolean regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len)中的一段代码注释
// Unfortunately, conversion to uppercase does not work properly// for the Georgian alphabet, which has strange rules about case// conversion. So we need to make one last check before// exiting.if(Character.toLowerCase(u1)== Character.toLowerCase(u2)){continue;}
publicintcompareToIgnoreCase(String str){// public static final Comparator<String> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator();return CASE_INSENSITIVE_ORDER.compare(this, str);}
10 concat:追加字符串到当前字符串
源码
public String concat(String str){int otherLen = str.length();if(otherLen ==0){returnthis;}int len = value.length;char buf[]= Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);returnnewString(buf,true);}