2010-11-08 173 views
1

我當前的項目需要搜索歌曲的歌詞,這是Song對象中的一個String字段。爲了幫助提高搜索效率,我使用String.split("[^a-zA-Z]");創建歌曲對象時將歌詞轉儲爲一個集合,以創建一個String數組,然後添加到一個集合中。有沒有比String.split()更有效的方式將字符串分解成單詞?

是否有一種特殊的方式來將單詞添加到一個集合中,而不需要創建數組的中間步驟?

回答

1

你是否在特定歌曲中搜索某些單詞?如果是這樣,你可能不需要爲此設置一個集合,你可以從你得到歌詞的點開始搜索。你可以使用這個簡單的正則表達式,這可能比分割字符串,把它變成一個集和查詢設置,那麼快的方式位:

public class RegexpExample { 

public static void main(String[] args) { 
    String song = "Is this a real life? Is this just fantasy?"; 
    String toFind = "is"; 

    Pattern p = Pattern.compile(toFind, Pattern.CASE_INSENSITIVE); 
    Matcher m = p.matcher(song); 

    while (m.find()) { 
     String found = m.group(); 
     int startIndex = m.start(); 
     int endIndex = m.end(); 

     System.out.println(found + " at start " + startIndex + ", end " + endIndex); 
     //do something with this info... 
    } 
} 

它會輸出這樣的:

Is at start 0, end 2 
is at start 5, end 7 
Is at start 21, end 23 
is at start 26, end 28 

如果您在不同的歌曲搜索。然而,你可以使用StringBuilder串連他們的歌詞,然後調用StringBuilder#toStringtoString方法的結果做整個操作

+0

當前項目正在運行搜索與特定單詞不匹配的特定單詞。您的解決方案似乎最適合短語搜索,這是下一個項目,我可能會實現您的答案。 – Jason 2010-11-09 13:02:22

1

是否有添加的話到一組,而無需創建一個陣列的 中間步驟以特定的方式?

當然,你可以編寫一個方法返回一個Iterator對象,該對象每次輸出一個單詞。

但是像這樣的東西真的不值得優化。你的數組很容易小到可以放進內存中,它的創建不會很昂貴,並且垃圾收集器將在之後清理它。

0
StringTokenizer st = new StringTokenizer("the days go on and on without you here"); 
HashSet<String> words = new HashSet<String>(); 
while (st.hasMoreTokens()) { 
    words.add(st.nextToken()); 
} 
+4

:它像這樣'的StringTokenizer是保持兼容性的原因,儘管其使用在新代碼氣餒的遺留類。建議任何尋求此功能的人都使用String或java.util.regex包的拆分方法。'有趣的解決方案,儘管 – Jason 2010-11-08 21:08:44

0

我不知道效率,但或者,你可以做根據的Javadoc

import java.io.StringReader; 

// ... 

public static Set<String> getLyricSet(String lyrics) throws IOException { 
    StringReader sr = new StringReader(lyrics); 
    StringBuilder sb = new StringBuilder(); 
    Set<String> set = new HashSet<String>(); 
    int current; 
    // Read characters one by one, returns -1 when we're done 
    while ((current = sr.read()) != -1) { 
     if (Character.isWhitespace(current)) { 
      // End of word, add current word to set. 
      set.add(sb.toString()); 
      sb = new StringBuilder(); 
     } else { 
      sb.append((char) current); 
     } 
    } 
    // End of lyrics, add current word to set. 
    set.add(sb.toString()); 
    sr.close(); 

    return set; 
} 
相關問題