我基本上想搜索字符串的频率。例如,如果我传入“我”这个词,那么下面这句话中这个词的频率:“我去了海滩,我看到了三个人”应该是 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,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)
关于java - 字符串的计数频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7830673/