FUNCTIONS

4. Write a Java method to count all the words in a string.

            class CountStr
            {
               int CountWord(  String str)
                {
                   
                      if(str==null || str.trim().isEmpty())
                         {
                            return 0;
                          }
                      String[] word1=str.trim().split("\\s+");
                   return word1.length;
            }
            }
            class main
            {
               public static void main(String st[])
                 {
                       CountStr obj=new CountStr();
                       System.out.println("number of characters are:"+obj.CountWord("this is a program"));
            }
            }
        

OUTPUT

            number of characters are:4