/** * Returns the longest string {@code suffix} such that * {@code a.toString().endsWith(suffix) && b.toString().endsWith(suffix)}, taking care not to * split surrogate pairs. If {@code a} and {@code b} have no common suffix, returns the empty * string. * * @since 11.0 */ public static String commonSuffix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxSuffixLength = Math.min(a.length(), b.length()); int s = 0; while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) { s++; } if (validSurrogatePairAt(a, a.length() - s - 1) || validSurrogatePairAt(b, b.length() - s - 1)) { s--; } return a.subSequence(a.length() - s, a.length()).toString(); }
/** * 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 */ public static 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(); }