Write a program to Count words in Given String


This code is used to count the number of occurrences of each word in a given string.

  • It first splits the input string into an array of words using the split() method, with a whitespace separator.
  • Then it uses two nested loops to compare each word in the array with all the remaining words, and counts the number of times a word occurs by incrementing a counter variable wrc.
  • If a word is repeated, it is marked as 0 to avoid counting it again, and the counter wrc is incremented.
  • Finally, the code prints out each unique word in the array along with its count.

Note that this code is case sensitive, so it will count "String" and "string" as two different words.

Source Code

public class CountWords 
{
   public static void main(String[] args)
   {
		String input="String and String function";
		String[] words=input.split(" ");
		int wrc=1;      
		for(int i=0;i<words.length;i++)    
		{
			for(int j=i+1;j<words.length;j++)
			{
				if(words[i].equals(words[j]))
				{
				   wrc=wrc+1;
				   words[j]="0";
				}
			}
			if(words[i]!="0")
				System.out.println(words[i]+" = "+wrc);
				wrc=1;         
		}         
   }
}

Output

String = 2
and = 1
function = 1

Example Programs