// IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark finalint len = string.length(); finallong longSize = (long) len * (long) count; finalint size = (int) longSize; if (size != longSize) { thrownew ArrayIndexOutOfBoundsException( "Required array size too large: " + longSize); }
finalchar[] array = newchar[size]; string.getChars(0, len, array, 0); int n; for (n = len; n < size - n; n <<= 1) { System.arraycopy(array, 0, array, n, n); } System.arraycopy(array, 0, array, n, size - n); returnnew String(array); }
/** * Returns the longest string {@code prefix} such that * {@code a.toString().startsWith(prefix) && b.toString().startsWith(prefix)}, * taking care not to split surrogate pairs. If {@code a} and {@code b} have * no common prefix, returns the empty string. * * @since 11.0 */ publicstatic String commonPrefix(CharSequence a, CharSequence b){ checkNotNull(a); checkNotNull(b);
int maxPrefixLength = Math.min(a.length(), b.length()); int p = 0; while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) { p++; } if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) { p--; } return a.subSequence(0, p).toString(); }
对了,你一定发现了,while 后面还跟着一个莫名其妙的 if,这是什么东西!函数名里面居然出现了我不认识的单词,查一下 surrogate pair 发现是代理对的意思。Google 一番之后发现原来是 Java 平台增补字符 惹的货。简单说这里其实是判断最后两个字符是不是合法的 “Java 平台增补字符” 。看起来这些增补字符占了 2 个字节,然后要用判断高位低位之类的。仔细看了函数的头注释,里面也提到 taking care not to split surrogate pairs,然后就明白了。