In Java write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount("hello") should return 1, the call wordCount("how are you?") should return 3, the call wordCount(" this string has wide spaces ") should return 5, and the call wordCount(" ") should return 0.

Respuesta :

Answer:

// here is code in java.

import java.util.*;

// class definition

class Main

{

   // method that return the number of words in the string

   public static int wordCount(String st)

   {

       /* split the string by space " " delimiter

       and save them into  string array*/

       String[] no_words=st.split(" ");

       // find the length of array

       int len= no_words.length;

       //return the length

       return len;

   }

   // driver function

public static void main (String[] args) throws java.lang.Exception

{

   try{

    // scanner object to read input string

       Scanner s=new Scanner(System.in);

        // string variable

       String str;

       //ask user to enter string

       System.out.print("please enter the string: ");

       // read the string from user

       str=s.nextLine();

       // call the function with string parameter

      int tot_words= wordCount(str);

      // print the number of word in string

      System.out.println("total words in the string is : "+tot_words);

   }catch(Exception ex){

       return;}

}

}

Explanation:

Read a string from user with the help of scanner class object.Call the function

wordCount() with string parameter.Here split the string by space " " delimiter.

Save the words into a string array.Find the length of the array and return it.

Then in the main print the number of words in the input string.

Output:

please enter the string: this string has wide spaces

total words in the string is : 5