2017-09-01 54 views
0

我試圖執行類似於拼寫檢查的行爲,但不完全相同。通過靜態,我的意思是隻在某些單詞上。靜態拼寫檢查行爲

讓我們說我有一個10個字符串的數組。

String[] originalWords = new String[] { 
     "Apple", "Banana", "Orange", "Pear", "Grape", 
     "Pineapple", "Lemon", "Mango", "Cherry", "Peach" 
}; 

現在,我有一個EditText用戶可以鍵入東西。用戶輸入完(他們按NEXT等)後,我想對他們在輸入進行檢查。

String userInput = String.valueOf(editText.getText()).trim(); 

比方說userInputappla。這意味着輸入的用戶只有一個字母Apple(位於數組中)。

這就是我要實施的檢查。無論用戶輸入什麼內容,如果數組中存在一個SIMILAR(1或2個字母關閉)字,我想獲取該字。我將如何去實施呢?

結果例子:

aoole ==> Apple 
orenge ==> Orange 
Cheery ==> Cherry 
+1

這就需要一個算法來找到字符串的相似性百分比..嘗試谷歌搜索'java比較字符串相似性' – ZeroOne

回答

0

我能想出解決辦法。它並不完全按照我想要的方式(1或2個字母),但是它完成了這項工作,因爲它提供了相似性的百分比。

我使用this庫。

// array of original words to compare against 
String[] originalWords = new String[] { 
     "Apple", "Banana", "Orange", "Pear", "Grape", 
     "Pineapple", "Lemon", "Mango", "Cherry", "Peach" 
}; 

// convert String array to ArrayList 
ArrayList<String> originals = (ArrayList<String>) Arrays.asList(originalWords); 

ExtractedResult extractedResult = FuzzySearch.extractOne("aoole", originals); 

if(extractedResult.getScore() >= 75) { 
    // the word provided (aoole) is at least 75% similar to one of the original words. 
    // To get the original word: 
    String result = extractedResult.getString(); 
}