2011-10-20 209 views
2

我基本上想要搜索字符串的頻率。例如,如果我傳遞了單詞「I」,那麼這個單詞的出現頻率如下:「I去了海灘和I看到三個人」應該是2.我已經構建了這樣的方法在其中我接受一個文本(任意長度),將它分割成一個數組,並通過數組循環遍歷數組,搜索每個索引是否與該單詞匹配。然後,我遞增頻率計數器並將該數字作爲字符串返回。這裏的方法:計算字符串的頻率

private int freq() { 
String text = "I went to the beach and I saw three people"; 
String search = "I"; 
String[] splitter = text.split("\\s+"); 
int counter = 0; 
    for (int i=0; i<splitter.length; i++) 
    { 
     if (splitter[i]==search) 
     { 
      counter++; 
     } 
     else 
     { 

     } 
    } 
    return counter; 
     } 

} 

這是法外:

String final = Integer.toString(freq()); 
System.out.println(final); 

但正如我運行它,我不斷收到0的結果。我不知道我做錯了什麼。

編輯:你們都是正確的!什麼是浪費問題:(的。

+0

爲HashMap的基本代碼,你得到了一個很好的HashMap了吧:)嚴重的,知道基本的數據結構和何時使用它們是巨大的。 –

回答

6

使用equals,而不是==

if (text[i].equals(search)) 
    { 
     counter++; 
    } 

更好的解決方案

使用地圖的話Map<String,Integer>與頻率圖。

String [] words = line.split(" "); 

Map<String,Integer> frequency = new HashMap<String,Integer>(); 

for (String word:words){ 

    Integer f = frequency.get(word); 
    //checking null 
    if(f==null) f=0; 
    frequency.put(word,f+1); 
} 

然後你可以找到與一個特定的詞:

frequency.get(word) 
+1

不錯的地圖解決方案! –

+1

我開始寫關於log(N)時間的評論,然後意識到Map被實例化爲一個接口(不起作用)。我將其改爲具體類型。兩個常見的Map實現是TreeMap和HashMap。 TreeMap是log(N)時間,但你可以將所有東西都排序。 HashMap會給你O(1)插入和O(1)查找。 –

2

使用equals()方法來比較字符串。

if(text[i].equals(search)) 
{ 
    counter++; 
} 
+1

我猜他的邏輯也不正確!他/她應該穿過「分離器」而不是文字:) – doNotCheckMyBlog

+0

那麼簡單嗎?哇!它的工作原理! –

+0

@程序員的確如此。 – adatapost

0

字符串應該與String.equals進行比較,而不是==,檢查,看看他們是相同的對象,而不是他們是否哈伯相同內容

0

要比較兩個String你必須使用equals()方法,而不是一個簡單的==

1
private int freq() { 
    String text = "I went to the beach and I saw three people"; 
    String search = "I"; 
    String[] splitter = text.split("\\s+"); 
    int counter = 0; 
/* problem: You want to be looping over splitter. */ 
    for (int i=0; i<text.length; i++) 
    { 
/* problem: splitter[i].equals(search) */ 
     if (text[i]==search) 
     { 
      counter++; 
     } 
    } 
    return counter; 
} 
0

對於你的代碼工作遵循其他答案,使用.equals而不是==,但你可以還使用Apache Commons Lang中:

StringUtils.countMatches(text, search); 

http://commons.apache.org/lang/ http://commons.apache.org /lang/apidocs/org/apache/commons/lang3/StringUtils.html#countMatches(java.lang.CharSequence,java.lang.CharSequence中)

0

您可以使用地圖把字作爲重點和詞的頻率值。然後在循環中,嘗試使用try-catch塊將+ 1添加到與當前單詞(tryblock)關聯的關鍵字,如果該單詞未找到,則「fdist.get(w)」將給出nullpointerexception,然後單擊1的值。

​​
+1

你的回答應該包含你的代碼的解釋和描述它是如何解決這個問題的。 – AbcAeffchen

0

確定文件中單詞的頻率。
這是Java

File f = new File(fileName); 
Scanner s = new Scanner(f); 
    Map<String, Integer> counts = 
    new Map<String, Integer>(); 
     while(s.hasNext()){ 
String word = s.next(); 
if(!counts.containsKey(word)) 
counts.put(word, 1); 
else 
counts.put(word, 
    counts.get(word) + 1); 
}