2011-11-02 89 views
0

我想比較兩個字符串的索引。基本上,如果字符串的第一個索引不等於第二個索引,請在void main中創建新的searchIndex()方法。比較java中字符串的索引

這表示如果用戶在2個單詞的搜索引擎中輸入查詢,結果應顯示第一個單詞的匹配文本文件和第二個單詞的匹配文本文件,而不是顯示匹配的總數並且將文本文件彼此混合而不知道哪個單詞與哪個文本文件相關。

如果我在文本框中

輸出進入Japan

Searching for 'Japan ' 
3 
Files\whalehunt.txt 
Files\japan.txt 
Files\innovation.txt 

但是,如果我進入了2個字:

輸出:

Searching for 'Japan amazon ' 
5 
Files\whalehunt.txt 
Files\japan.txt 
Files\peru.txt 
Files\correspondent.txt 
Files\innovation.txt 

在2個字的情況下,用戶不知道哪個文件是哪個文件。這一切都混在一起。我正在嘗試做的是比較查詢字符串的索引以匹配兩個單詞是否相同。如果不是,則應在void main中添加新的searchIndex()方法,併爲其分配第二個單詞。

所以,與其這樣:

public static void main(String[] args) throws Exception { 

     createIndex(); 

     searchIndex("Japan amazon "); 

    } 

這樣做:

public static void main(String[] args) throws Exception { 

      createIndex(); 

       searchIndex("Japan "); 
       searchIndex("amazon"); 


     } 

我曾嘗試是:

public static void searchIndex(String searchString) throws IOException, ParseException { 

     for(int n=0;n<=1000;n++) 
     { 
      if (searchString.substring(0) != searchString.substring(1)) 
      { 

       void main.searchIndex(searchString.); //**Error** 
      } 
     } 

任何幫助將不勝感激!

問候。

回答

1

你serachIndex()方法是完全錯誤的,恕我直言。您正在比較字符串的索引0和1 1000次。爲什麼不使用標記器或String.split()從字符串中分離單詞?事情是這樣的:

public static void searchIndex(String searchString) throws IOException, ParseException { 
    searchString = searchString.trim(); 
    if (searchString.length < 1) 
     return; 
    String[] words = searchString.split(" "); 
    if (words.length > 1) { 
     for (String word : words) 
      searchIndex(word); 
    } else { 
      // Do normal stuff here 
    } 
} 

順便說一句,我以爲你是知道的像Apache Lucene工具和算法,如MapReduce

+0

請看我的答案帖子,謝謝 – HShbib

+0

它的工作分裂了兩個單詞,顯示結果,但也顯示了舊日本的結果,這是日本亞馬遜結合在一起 – HShbib

0

您可以用break迭代器或使用更簡單的字符串標記

public static void breakSentenceIntoWords(String source) { 
     BreakIterator boundary = BreakIterator.getWordInstance(); 
     boundary.setText(source); 
     int start = boundary.first(); 
     for (int end = boundary.next(); 
       end != BreakIterator.DONE; 
       start = end, end = boundary.next()) { 
       String newWordToSearch = source.substring(start+1,end); 
       // perform search and other ops here 
     } 
    } 
+0

感謝您的回覆,我把我在代碼中提供的代碼放在哪裏? – HShbib

+0

你可以調用searchIndex(),我已經提到newWordToSearch作爲參數並連接結果,請隨時重新考慮以滿足您的需求。乾杯! – r0ast3d