-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP41_CountWordsInSentence.java
More file actions
48 lines (40 loc) · 1.33 KB
/
Copy pathP41_CountWordsInSentence.java
File metadata and controls
48 lines (40 loc) · 1.33 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
47
48
package programs;
/**
* ============================================================
* PROGRAM 41: Count Words in a Sentence
* ============================================================
* Problem: WAP to count total words in a sentence without using `split()`.
* Handles multiple consecutive spaces, leading/trailing whitespace.
* ============================================================
*/
public class P41_CountWordsInSentence {
public static int countWords(String sentence) {
if (sentence == null || sentence.trim().isEmpty()) return 0;
int wordCount = 0;
boolean inWord = false;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (!Character.isWhitespace(ch)) {
if (!inWord) {
wordCount++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCount;
}
public static void main(String[] args) {
String[] samples = {
"Java is awesome",
" Welcome to the course ",
"OneWord",
"",
" "
};
for (String s : samples) {
System.out.printf(" \"%s\" -> Word Count: %d%n", s, countWords(s));
}
}
}