字符串的计数频率 [英] Counting frequency of a string

查看:173
本文介绍了字符串的计数频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上要搜索的字符串的频率。例如,如果我通过在我,然后在下面的句子中词的频率:去了海滩和只见三人应该是2,我已经构造中,我采取(任意长度的)文本这样的方法,将它分成数组的空白,并遍历数组,如果每个指标匹配单词搜索。然后,我递增频率计数器,并返回数为字符串。这里的方法:

I essentially want to search the frequency of a string. For example, if I pass in the word "I", then the frequency of the word in the following sentence: "I went to the beach and I saw three people" should be 2. I've constructed such method in which I take a text (of any length), split it into an array by the white space, and loop through the array, searching if each index matches the word. Then, I increment the frequency counter and return the number as a string. Here's the method:

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作为结果。我不知道我做错了。

But as I run this, I keep getting 0 as the result. I don't know what I'm doing wrong.

编辑:你是正确的!什么是一个问题:(。

You're all correct! What a waste of a question :(.

推荐答案

使用等于而不是 ==

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

更好的解决方案

使用一个Map的话地图&LT地图,字符串,整数方​​式&gt; 频率

Use a Map to map the words Map<String,Integer> with frequency.

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);
}

然后你就可以找出一个特定的词:

Then you can find out for a particular word with:

frequency.get(word)

这篇关于字符串的计数频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆