How to count number of words in File in Java

Price: INR 1,299.00
Was: INR 1,799.00

Let’s see, How can you count number of words in File in Java. To perform this first we need to read the file, You can refer how to read a file in Java. After that, we need to keep the file content in a String and then count the number of words in that String.

 

Count Number of Words in File

To implement this scenario, You need to implement the method which will accept the string as a parameter and return the number.
Many peoples have personal collections of such questions which they revise every time they go for a Programming job interview, but if you don’t have any yet, then don’t worry.

Count Number of Words in String

We know that words in the string are separated by white space, which could be space or tabs. So if you split the String by whitespace, you can get an array of String which is nothing but words.  Now the length of this array is your number of words, just return that.

But, you need to be a little bit careful because there is also a possibility of more than one space between two words. So simply using a regular expression to catch space or tab will not be enough, you need to use a greedy regular expression to catch multiple spaces as well.

In Java, you can use the regular expression pattern “\\s+” to catch multiple spaces. The “\s” is a character class to find white space, which could match both space and tabs and “+” makes it greedy because it will match one or more of “\s” pattern i.e. one or more space. Now, since you need to escape the “\”  backward slash in Java, the whole pattern becomes”\\s+”.  So the final implementation will look like –

That’s all about how to count a number of words in a given File in Java. The regular expression solves this problem in a couple of lines, but as a challenge, can you solve this problem without using regular expression.

1 Comment
  1. Java Programming 9:05 PM / September 27, 2016 - Reply

    Hi Easy Bix,

    Great tip for using Java. This tutorial can help save time for beginner Java users.

    Thanks,
    Dennis

Leave a Reply