I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount);
}
}
To count total words Or to count total words without repeat word count
}
Output :
Total words Count==7
Count without Repeatation ==5
Java does have
StringTokenizer
API and can be used for this purpose as below.OR
in a single line as below
StringTokenizer
supports multiple spaces in the input string, counting only the words trimming unnecessary spaces.Above line also prints 5
}
This could be as simple as using split and count variable.
To count specified words only like John, John99, John_John and John's only. Change regex according to yourself and count the specified words only.