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;
}
}
This is outside the method:
String final = Integer.toString(freq());
System.out.println(final);
But as I run this, I keep getting 0 as the result. I don’t know what I’m doing wrong.
EDIT: You’re all correct! What a waste of a question :(.
Use
equalsinstead of==better solution
Use a Map to map the words
Map<String,Integer>with frequency.Then you can find out for a particular word with: