Q:

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

belongs to collection: Java String Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check given strings are Anagram or... >>
<< Easiest way to check Given String is Palindrome St...