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);
}
}
try this
You can use
String.split
(read more here) instead of charAt, you will get good results. If you want to usecharAt
for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra wordThe ideas is to split the string into words on any whitespace character occurring any number of times. The split function of the String class returns an array containing the words as its elements. Printing the length of the array would yield the number of words in the string.
You need to read the file line by line and reduce the multiple occurences of the whitespaces appearing in your line to a single occurence and then count for the words. Following is a sample: