Repository navigation
Expand file tree
/
Copy pathDay21.java
More file actions
50 lines (33 loc) · 1.36 KB
/
Copy pathDay21.java
File metadata and controls
50 lines (33 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package JHomeworks;
import java.util.Arrays;
import java.util.Scanner;
//Write a Java method to count all words in a string. Go to the editor
// Test Data:
// Input the string: The quick brown fox jumps over the lazy dog.
// Expected Output:
// Number of words in the string: 9
//advanced, put in a new class and call the method from the main method
public class Day21 {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog.";
String[] words = sentence.split(" ");
System.out.println(Arrays.toString(words));
System.out.println("length = " + words.length);
System.out.println("************************************");
Scanner in = new Scanner(System.in);
System.out.println("Input the string :");
String str = in.nextLine();
System.out.println("number of words in the string:" + wordCount(str));
}
private static int wordCount(String sentence) {
int count = 0;
char ch[] = new char[sentence.length()];
for (int i = 0; i < sentence.length(); i++) {
Character letterChar = sentence.charAt(i);
ch[i] = sentence.charAt(i);
if (((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' ')) || ((ch[0] != ' ') && (i == 0)))
count++;
}
return count;
}
}