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

This java program will read a string and returns the total number of words in an input string; here, we are counting the total number of words in a 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

Java String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.