• Post Reply Bookmark Topic Watch Topic
  • New Topic

find word occurence in string  RSS feed

 
r bal
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might need to have a check condition, rather than simply add the count.



Nick
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!