2016-02-26 103 views
0

即使格式不匹配,我想要搜索字符串例如 「蘋果」是字符串我試圖搜索,但我輸入「蘋果」或「ápple」或「Applé」。我想檢查我輸入的每個字符, 如果它不匹配字符串,我試圖搜索它將替換它,直到我得到字符串「蘋果」。檢查字符串字符,如果它不匹配它將取代

+5

這是沒有意義的。只需強制用戶輸入Apple,因爲無論如何您都可以替換。 – Tunaki

+0

@ user3659052我的專家說它會使它在搜索中更加用戶友好。就像谷歌一樣,如果你拼錯了這個詞,它會糾正拼寫錯誤的單詞並給你正確的答案。但任何建議將很好 –

+1

可能的重複[什麼是相當於stringByFoldingWithOptions:語言環境:在Java?](http://stackoverflow.com/questions/21489289/what-is-the-equivalent-of-stringbyfoldingwithoptionslocale-in -java) – twernt

回答

1

你的問題並不完全清楚,但它聽起來像你可能試圖計算兩個字符串之間的Levenshtein距離。如果你對這個術語做了一點研究,應該清楚這是否是你需要的。

簡而言之:

的Levenshtein距離是缺失,插入或取代來改造「蘋果」到「蘋果」所需要的數目。

2

您可能有興趣在下面的代碼看起來爲使用較大標準化字符串內的歸一化字符串java.text.Normalizer

此類提供其將Unicode文本到構成的等價物或方法normalize分解形式,允許更簡單的排序和搜索文本。 normalize方法支持Unicode Standard Annex #15 — Unicode Normalization Forms中描述的標準規範化表單。

Sample code

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.text.Normalizer; 

class Ideone 
{ 
    public static void main(String[] args) { 
     String haystack[] = {"Apple","Apple","Apple"}; // sample input strings 
     String needle[] = {"ápple", "apple", "Applé"}; // sample keywords 
     for (int i = 0; i < haystack.length; i++) { // loop through inputs 
      System.out.println(
       find(
         normalize(haystack[i]),   // get the normalized form of input 
         normalize(needle[i])   // get the normalized form of the keyword 
       ) 
      ); 
     } 
    } 

    public static String normalize(String s) {  // Get the string without diacritics 
     return Normalizer.normalize(s, Normalizer.Form.NFD).replaceAll("\\p{Mn}", ""); 
    } 

    // Checks if a string contains another in a case-insensitive way 
    public static boolean find(String haystack, String needle) { 
     Pattern p = Pattern.compile(needle, Pattern.CASE_INSENSITIVE); 
     Matcher m = p.matcher(haystack); 
     if (m.find()) { 
      return true; 
     } else { 
      return false; 
     } 

    } 
} 
+0

這與我試圖做的事情非常接近。謝謝! @WiktorStribiżew 即時通訊使用Sqlite和即時通訊獲取名稱的數據即使用戶試圖搜索錯誤的輸入它仍然會給你最接近的數據。 –

+0

如果*最接近*表示*類似*,那麼您應該真的開始尋找基於Levenstein距離的解決方案。如果您對僅使用無變音的比較感興趣,我的解決方案就足夠了。 –

+0

我覺得它對我來說太複雜了。我只是一個初學者,我正在做一個硬編碼的開關盒。任何基本的建議? @WiktorStribiżew –

相關問題