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;}
}
}
Step-by-step 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