Hey Guys, I have a hw assignment and as the title says, it's counting words in a string. I obviously know this is a common problem but I'm trying to avoid finding an answer and instead just a little guidance in which way to look. I understand looking at each character with a for loop and to see if they are letters.
The problem I can't figure out is how to count up words even when there is ?? or -- or anything that is not a letter no matter how many none letter characters there are between words. Any help is appreciated. Thanks guys.
UPDATE: Hey Guys, thanks for your help I figured it out and figured I'd put the code here. I appreciate all your help.
import java.util.Scanner;
public class CountWords
{
public static void main(String[] args)
{
String sentence;
String divide=" .,;?-!";
int word = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string >> ");
sentence = keyboard.nextLine();
for (int x=0; x < sentence.length(); ++x)
for (int y=0; y < divide.length(); ++y)
if((sentence.charAt(x) == divide.charAt(y)) && (Character.isLetter(sentence.charAt(x-1))))
++word;
System.out.println("There are " + word + " words in the string");
}
}
view the rest of the comments →
[–] tragicwhale [S] ago
Hey Phantom, It actually doesn't consider ?? a word. If the string was "This is ????? my ----- homework." It should calculate it to 4 words. Thanks for any help.
[–] thephantompoop 0 points 1 point 1 point (+1|-0) ago (edited ago)
I had a whole explanation written out, but the page refreshed and i lost it and i need to write an essay soon -,-
So here's the run-down
after you assign the sentence to a string, you should use
This removes all non-whitespace and non-letter/number characters. You string will be "This is my homework".
After this,
This turns sentence into a static array of length 4:
A handy site to explain what I just did:
Regex
A handy site for testing regex with a quick reference chart at the bottom:
Rubular
[–] tragicwhale [S] 0 points 1 point 1 point (+1|-0) ago
Hey Phantom, That is spectacular information as I had never seen those methods before. Thanks for the website too as it's just another tool in my toolbox. Really appreciate all the help.