Java Program to Get String and Count Number of Words in Provided String

You are currently viewing Java Program to Get String and Count Number of Words in Provided String

Java program to get string and count number of words in provided string

package com.includehelp.stringsample;

import java.util.Scanner;

/**
 * program to get string and count no. of words in provided string
 * @author includehelp
 */
public class CountWordsInString {
    
    /**
     * Method to count no. of words in provided String
     * @param inputString
     * @return 
     */
    static int countWords(String inputString){
        String[] strarray = inputString.split(" ");  // Spilt String by Space
        StringBuilder sb = new StringBuilder();
        int count=0;
        for(String s:strarray){
            if(!s.equals("")){
               count++;
            }    
        }
        return  count;
        
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter String : ");
        String str = sc.nextLine();
        System.out.println("No. of Words in String : "+countWords(str));
    }
    
    
}

Output

Enter String : Hello This is India
No. of Words in String : 4

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply