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
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
You are incrementing the counter if the character is some alphabet character. You should increment it if it is no alphabet character.
Your suggestion to use a regex like "[A-Za-z]" would work fine. In a split command, you'd split on the inverse, like:
String[] words = "Example test: one, two, three".split("[^A-Za-z]+");
EDIT: If you're just looking for raw speed, this'll do the job more quickly.
public static int countWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}