aspose file tools
The moose likes Beginning Java and the fly likes find word occurence in string Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "find word occurence in string" Watch "find word occurence in string" New topic
Author

find word occurence in string

r bal
Greenhorn

Joined: Mar 31, 2005
Posts: 6
Hi,

I am trying to write a program which returns the numbers of times a particular word is found in a String.

So far I have this code below...but it's definitely not working. Any help would be much appreciated. :-)


import javax.swing.*;

public class Sentence {

private static final char SPACE = ' ';

public static void main(String[] args) {

String inputSent, inputWord, error;
int count = 0;
int index = 0;
int numberOfCharacters;

inputSent = JOptionPane.showInputDialog(null, "Enter your sentence.");

inputWord = JOptionPane.showInputDialog(null,
"Enter the word you want to find in your sentence.");

numberOfCharacters = inputSent.length();

String space = " ";

while (index < numberOfCharacters) {
inputSent.indexOf(inputWord);
count++;
index++;

}

JOptionPane.showMessageDialog(null, "The word " + inputWord + " appears " + count + " times in the sentence " + "\n" + inputSent);

System.exit(0);

}

}
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2341
One problem I see is with your use of indexOf. indexOf will give you the
index of the first occurence of the word. You need to look at the other version of indexOf that will let you specify where to start looking.
r bal
Greenhorn

Joined: Mar 31, 2005
Posts: 6
Hi,

I have had another look at the API, and found....

"indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index."

So I changed that part of my code to:
while (index < numberOfCharacters) {
inputSent.indexOf(inputWord, index);
count++;
index++;

}

However, I keep getting the same results/errors.
Nicholas Cheung
Ranch Hand

Joined: Nov 07, 2003
Posts: 4982
You might need to have a check condition, rather than simply add the count.



Nick


SCJP 1.2, OCP 9i DBA, SCWCD 1.3, SCJP 1.4 (SAI), SCJD 1.4, SCWCD 1.4 (Beta), ICED (IBM 287, IBM 484, IBM 486), SCMAD 1.0 (Beta), SCBCD 1.3, ICSD (IBM 288), ICDBA (IBM 700, IBM 701), SCDJWS, ICSD (IBM 348), OCP 10g DBA (Beta), SCJP 5.0 (Beta), SCJA 1.0 (Beta), MCP(70-270), SCBCD 5.0 (Beta), SCJP 6.0, SCEA for JEE5 (in progress)
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: find word occurence in string
 
Similar Threads
sorting an array
why does this code work
Incompatible types
Problems with counting short and long words
need help