Latest Tutorials| Questions and Answers|Ask Questions?|Site Map

Home Answers Viewqa Java-Beginners Count words in a string method?

Have Programming Question? Ask it here!

Naulej kumar
Count words in a string method?
1 Answer(s)      2 years and 2 months ago
Posted in : Java Beginners

How do you Count words in a string?

View Answers

June 28, 2012 at 5:59 PM


package RoseIndia;

import java.util.StringTokenizer;

public class StringCount {
    public static void main(String [] args){
  BufferedReader br = 
          new BufferedReader(new InputStreamReader(;
     System.out.print("Enter string: ");
     String st=br.readLine();

     int count=0;

     String arr[]=st.split(" ");

     System.out.println("Number of words : "+arr.length);
      }catch(IOException e){


Enter string: hi how are you
Number of words : 4

Description: This example counts the number of words into inputted String. Here st is user-inputted string. BufferedReader is used for user input. split()method is used for splitting the given string according to given pattern. In above example we are splitting st by pattern ?? ?? ie by space. arr[] is String type array in which we are storing string after splitting. Now count the length of arr which return the number of words in the inputted string.

Related Tutorials/Questions & Answers: