计算字符串的频率

我基本上想要搜索字符串的频率。 例如,如果我传入单词“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。 我不知道我做错了什么。

编辑:你们都是对的! 多么浪费一个问题:(。

使用equals而不是==

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

更好的解决方

使用Map以频率映射单词Map

 String [] words = line.split(" "); Map frequency = new HashMap(); for (String word:words){ Integer f = frequency.get(word); //checking null if(f==null) f=0; frequency.put(word,f+1); } 

然后你可以找到一个特定的单词:

 frequency.get(word) 

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

 if(text[i].equals(search)) { counter++; } 
 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 

字符串应该与String.equals进行比较,而不是==,它会检查它们是否是同一个对象 ,而不是它们是否具有相同的内容

要比较两个String你必须使用equals()方法而不是简单的==

为了使代码能够按照其他答案进行操作,请使用.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)

您可以使用Map将单词作为键的关键和频率作为值。 然后在循环内部,尝试使用try-catch块将+ 1添加到当前单词的关键字(tryblock),如果找不到单词“fdist.get(w)”则会给出nullpointerexception,然后用简单的put来捕获1为价值。

 Map fdist = new HashMap(); for(String w:s.split(" ")){ try { fdist.put(word, fdist.get(w)+1); } catch (Exception e) { fdist.put(word, 1); } } 

确定文件中单词的频率。
这是java中hashmap的基本代码

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