I need to count the number of words and I am assuming the correct way to do it is by calculating the number of times that the previous character in a string is not a letter (ie other characters) because this is to assume that there would be colons,spaces,tabs, and other signs in the string. So at first my idea was to loop through each character and count how many times that you will not get a letter of an alphabet
for(int i = 0; i < string.length(); i++) {
for(int j = 0; i < alphabets.length(); j++) {
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
}
}
However I will always get an array out of bounds because of this. So, I kinda need a little help or another way that can actually be more efficient. I thought of using Matches to only [a-zA-z] but I'm not sure how do I handle a char to be comparable to a string in counting how many times it occurs.
Thank you
The following program will count the number of words in a sentence. In this program, we are counting alphabets just after space. The alphabet can be of lower case or upper case. We are inserting a space at the beginning since people don't start a sentence with space. We also need to take care that any special character or number should not be counted as a word.
`import java.util.Scanner; public class WordSent {
This problem is slightly more complicated than your algorithm allows.
This looks like homework, so I don't want to provide any code. I suggest an alternative approach which is simpler to think about.