searching char array with another char array for full word matches
Hi all,
I am very new to Java (Semester 1 of university) and I am having trouble trying to figure out an algorithm to search a char array with another char array to find word matches.
I have tried using two for-loops and finding word matches like so:
Code:
public static void main(String[] args) {
String textToSearch = "the quick brown fox jumped over the lazy dog quick quick";
String searchTerm = "quick";
int charMatches =0;
char[] textToSearchArray = textToSearch.toLowerCase().toCharArray();
char[] searchTermArray = searchTerm.toLowerCase().toCharArray();
for (int i=0; i < textToSearchArray.length; i++)
{
for (int j=0; j < searchTermArray.length; j++)
{
if (textToSearchArray[i]==searchTermArray[j])
charMatches ++;
}
}
System.out.println("The number of word matches are: "+(charMatches/searchTermArray.length));
}
If I run this code, it returns a correct number of word matches (3)......but if I change the textToSearch string to "hello hello hello" and the searchTerm string to "hello", it tells me that there are 4 matches?
I think it is because the "l"s are counted twice and I am pretty sure this algorithm of mine is not a really good way to go about the task.
DISCLAIMER: yes, this is for a homework assignment, but I have tried Googling for a solution, reading books and working it out on paper... I really want to understand how to do this and any help would be greatly appreciated .