How to count the number of words in a string in Java

This tutorial consists of two ways to count the number of words in a string in Java:

  • Using a String Tokenizer class.
  • Using the CommandLine itself.

StringTokenizer Class

What is this StringTokenizer class?

StringTokenizer is a class whose object tokenizes a given String. A StringTokenizer class can have up to three constructors:

  1. String: The string which is to be tokenized.
  2. delim: which are delimiters(such as space, tab etc.) which tokenizes the given String.
  3. flag: if the flag is false, delimiters are used to separate the tokens, or if the flag is true, delimiters are themselves considered as tokens.

In the code given down below, a WordsInAString class has a single String, which is passed as it’s the constructor.  The class has one stringLength( ) method which calculates the number of words in the String.

At first, we create a StringTokenizer class. A variable identified as length holds the number of words in the String. The countTokens( ) method is a method in StringTokenizer class which counts the number of tokens in the String, keeping in account the type of delimiters used. In this code, no delim parameter is used in the countTokens( ) method and hence the delimiter used by the StringTokenizer class is the default space or tab. The length is then printed. The code for the problem is as follows :

Count the number of words in a string in Java

import java.util.Scanner;
import java.util.StringTokenizer;
public class WordsInAString{
  String str;
  public WordsInAString(String str){
    this.str = str;
  }
  public void stringLength(){
    if(str.isEmpty()||str == null){
      System.out.println("There are no words in the sentence.\n");
    }
    else{
      StringTokenizer words = new StringTokenizer(str); //StringTokenizer class object is created
      int length = words.countTokens();  //countTokens() method counts the number of words
      System.out.println("There are "+length+" words in the Sentence."); //print the length
    }
  }
}



class Test{
  public static void main(String args[]){
    Scanner s = new Scanner(System.in);
    String input;
    System.out.println("\nEnter a String.");
    input = s.nextLine();
    WordsInAString w = new WordsInAString(input);
    w.stringLength();
  }
}

 

A single line of input is given which contains the String. The output is the number of words in the String.

Output

Enter a String.
Welcome to codespeedy

There are 3 words in the sentence.

 

Using Command-Line Input: Count the number of words in a string

The command-line technique is rather a very simple technique of calculating the number of words in the sentence. It uses the String arguments passed in the main method.

For example:
If the input string is Welcome to codespeedy, args[0] gets assigned with Welcome, args[1] gets assigned with to and args[2] gets assigned with codespeedy.   Hence when args.length( ) function is called, it returns the number of words in the String.

Code

import java.util.*;

public class WordsInAString {
  public static void main(String[] args){
    System.out.println("The sentence has " + args.length + " words"); 
  }
}

Output

After compilation of the .java file in command-line, the .class file is created. Now when executing this class file, the general syntax followed is java <classname> .  The String input is given at the time of executing this class file itself as java <classname> Welcome to codespeedy .

Hence, the output will be :

The sentence has 3 words

So that’s all in this tutorial. All the best!
Also Read: An Object Oriented Approach of using Math.addExact( ) method in Java

Leave a Reply

Your email address will not be published. Required fields are marked *