1package com.company;
2import java.util.*;
3
4public class Main{
5 public static int countWords(String s)
6 {
7 int count=0;
8
9 char ch[]= new char[s.length()];
10 for(int i=0;i<s.length();i++)
11 {
12 ch[i]= s.charAt(i);
13 if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
14 count++;
15 }
16 return count;
17 }
18 public static void main(String[] args) {
19 Scanner in = new Scanner(System.in);
20 System.out.print("Give word:");
21 String word = in.nextLine();
22 System.out.println(countWords(word) + " words.");
23 }
24}
1 public static void main(String[] args)
2 {
3 //return the number of words in a string
4
5 String example = "This is a good exercise";
6
7 int length = example.split(" ").length;
8
9 System.out.println("The string is " + length + " words long.");
10
11
12 }
1 String name = "Carmen is a fantastic play"; //arbitrary sentence
2
3 int numWords = (name.split("\\s+")).length; //split string based on whitespace
4 //split returns array - find legth of array
5
6 System.out.println(numWords);
1public static void main(String[] args)
2 {
3 //Scanner object instantiation
4 Scanner dude = new Scanner(System.in);
5
6 //variable declaration
7 String string1 = "";
8 int count = 0;
9 boolean isWord = false;
10
11
12 //user prompt and input
13 System.out.println("Enter in your string");
14 string1 = dude.nextLine();
15
16 int endOfLine = string1.length()-1;
17 char ch [] = string1.toCharArray();
18
19 for (int i = 0; i < string1.length(); i++)
20 {
21 if(Character.isLetter(ch[i]) && i != endOfLine)
22 {//if character is letter and not end of line
23 isWord = true; //it is part of a word
24 }
25 if (!Character.isLetter(ch[i]) && isWord)
26 { //if character is not a letter, and previous
27 //character is a letter i.e. non-letter is
28 //preceded by character
29 count++; //add to word count
30 isWord = false; //get ready to detect new word
31 }
32 if (Character.isLetter(ch[i]) && i == endOfLine)
33 { //if character is letter
34 //and at end of line
35 count++; //add to word count
36 isWord = false;
37 }
38
39 }
40 System.out.println("There are " +count+ " words");
41 }