1 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
一般來說,我建議使用Collator強(qiáng)度設(shè)置為 的Collator.PRIMARY來比較包含重音符號(hào)和不同大小寫的字符串(例如,Nvsn和évs e)。不幸的是,Collator沒有contains()功能。
所以我們將自己制作。
private static boolean contains(String source, String target) {
if (target.length() > source.length()) {
return false;
}
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
int end = source.length() - target.length() + 1;
for (int i = 0; i < end; i++) {
String sourceSubstring = source.substring(i, i + target.length());
if (collator.compare(sourceSubstring, target) == 0) {
return true;
}
}
return false;
}
這會(huì)迭代源字符串,并檢查與搜索目標(biāo)長度相同的每個(gè)子字符串是否等于搜索目標(biāo)(就 Collator 而言)。
例如,假設(shè)我們的源字符串是,"This is a Tèst"并且我們正在搜索單詞"test"。此方法將迭代每個(gè)四個(gè)字母的子字符串:
This
his
is i
s is
is
is a
s a
a T
a Tè
Tès
Tèst
一旦找到匹配項(xiàng)就會(huì)返回 true。由于強(qiáng)度設(shè)置為Collator.PRIMARY,整理器認(rèn)為"Tèst"和"test"相等,因此我們的方法返回true。
此方法很可能需要進(jìn)行更多優(yōu)化,但這應(yīng)該是一個(gè)合理的起點(diǎn)。
編輯RuleBasedCollator:一種可能的優(yōu)化是利用排序規(guī)則鍵以及and的已知實(shí)現(xiàn)細(xì)節(jié)RuleBasedCollationKey(假設(shè)您的項(xiàng)目中有 Google 的 Guava):
private static boolean containsBytes(String source, String target) {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
byte[] sourceBytes = dropLastFour(collator.getCollationKey(source).toByteArray());
byte[] targetBytes = dropLastFour(collator.getCollationKey(target).toByteArray());
return Bytes.indexOf(sourceBytes, targetBytes) >= 0;
}
private static byte[] dropLastFour(byte[] in) {
return Arrays.copyOf(in, in.length - 4);
}
這是相當(dāng)脆弱的(可能不適用于所有語言環(huán)境),但在我的測(cè)試中,它的速度快了 2 倍到 10 倍。
編輯:要支持突出顯示,您應(yīng)該轉(zhuǎn)換contains()為indexOf(),然后使用該信息:
private static int indexOf(String source, String target) {
if (target.length() > source.length()) {
return -1;
}
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
int end = source.length() - target.length() + 1;
for (int i = 0; i < end; i++) {
String sourceSubstring = source.substring(i, i + target.length());
if (collator.compare(sourceSubstring, target) == 0) {
return i;
}
}
return -1;
}
然后你可以像這樣應(yīng)用它:
String guestWholeName = guest.getGuestFirstName() + " " + guest.getGuestLastName();
int wholeNameIndex = indexOf(guestWholeName, searchText);
if (wholeNameIndex > -1) {
Timber.d("guest name first : guest.getGuestFirstName() %s", guest.getGuestFirstName());
Timber.d("guest name last : guest.getGuestLastName() %s", guest.getGuestLastName());
int endPos = wholeNameIndex + searchText.length();
Spannable spannable = new SpannableString(guestWholeName);
Typeface firstNameFont = Typeface.createFromAsset(context.getAssets(), "fonts/Graphik-Semibold.otf");
spannable.setSpan(new CustomTypefaceSpan("", firstNameFont), wholeNameIndex, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Objects.requireNonNull(guestName).setText(spannable);
} else {
Objects.requireNonNull(guestName).setText(guestWholeName);
}
添加回答
舉報(bào)