Thursday, January 30, 2014

Finding the Number of Words in a String

Write a program to find he Number of Words in a String


import java.util.Scanner;


public class NoOfWordsInAString {


    public static void main(String[] args) {


        Scanner sc=new Scanner(System.in);
        System.out.println("Enter your string:-");
        String str=sc.nextLine();
        int strLen=str.length();
        int word=1;
        for(int i=0;i<strLen-1;i++)
        {
            if((str.charAt(i))==' ')
            {
                word++;
            } 
        }
        System.out.print("The Number of words in the Given String are :" +word);
    }

}

OUTPUT:-

Enter your string:-
java test


The Number of words in the Given String are :2




No comments:

Post a Comment