count words in a string no numbers code example
Example 1: count the number of words in a string java
public static void main(String[] args)
{
String example = "This is a good exercise";
int length = example.split(" ").length;
System.out.println("The string is " + length + " words long.");
}
Example 2: program code for counting the similarwrod in the sentences
public static int count(String word) {
if (word == null || word.isEmpty()) {
return 0;
}
int wordCount = 0;
boolean isWord = false;
int endOfLine = word.length() - 1;
char[] characters = word.toCharArray();
for (int i = 0; i < characters.length; i++) {
if (Character.isLetter(characters[i]) && i != endOfLine) {
isWord = true;
} else if (!Character.isLetter(characters[i]) && isWord) {
wordCount++;
isWord = false;
} else if (Character.isLetter(characters[i]) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}