find number of words in string 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: 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;
}