Results 1 to 3 of 3
- 03-08-2011, 06:08 AM #1
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
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:
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?Java 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)); }
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 .
- 03-08-2011, 06:17 AM #2
Why are you fannying about with char arrays? Just use the methods of the String class.
Java Code:String words = "one two three"; String search = "two"; System.out.println(words.contains(search)); System.out.println(words.indexOf(search));
- 03-08-2011, 06:20 AM #3
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
convert byte array into char array
By kgkamaraj in forum New To JavaReplies: 4Last Post: 09-13-2011, 11:32 AM -
array to single char
By rfviki in forum New To JavaReplies: 5Last Post: 11-04-2010, 02:58 PM -
create a 2d char array from a 1D string array
By jschmall12 in forum New To JavaReplies: 1Last Post: 04-27-2010, 09:01 PM -
array of char
By sinisab in forum New To JavaReplies: 9Last Post: 01-05-2010, 09:48 AM -
Convert Char Array to String Array
By Mayur in forum New To JavaReplies: 8Last Post: 10-12-2009, 11:41 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks