count words into string code example
Example 1: check how many of a word is in a string
function countOccurences(str,word)
{
String a[] = str.split(",");
int count = 0;
for (int i = 0; i < a.length; i++)
{
if (word.equals(a[i]))
count++;
}
return count;
}
Example 2: how to count number of words in a string
String name = "Carmen is a fantastic play";
int numWords = (name.split("\\s+")).length;
System.out.println(numWords);
Example 3: 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;
}