Home » Java programs » Java string programs

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




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.