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
I can't just count the spaces though right because if I have "This is ?? a --- sentence." It'll count 7 spaces, unless I'm not reading your aid correctly. Thanks for your help.