Skip to content

Commit ab981f3

Browse files
authored
Merge pull request #7 from Raghav-Gupta22/patch-1
Create WordCounter.java
2 parents 9f7f6d7 + c29394e commit ab981f3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

WordCounter.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
public class demo {
2+
3+
static final int OUT = 0;
4+
static final int IN = 1;
5+
6+
// returns number of words in str
7+
static int countWords(String str)
8+
{
9+
int state = OUT;
10+
int wc = 0; // word count
11+
int i = 0;
12+
13+
// Scan all characters one by one
14+
while (i < str.length())
15+
{
16+
// If next character is a separator, set the
17+
// state as OUT
18+
if (str.charAt(i) == ' ' || str.charAt(i) == '\n'
19+
|| str.charAt(i) == '\t')
20+
state = OUT;
21+
22+
23+
// If next character is not a word separator
24+
// and state is OUT, then set the state as IN
25+
// and increment word count
26+
else if (state == OUT)
27+
{
28+
state = IN;
29+
++wc;
30+
}
31+
32+
// Move to next character
33+
++i;
34+
}
35+
return wc;
36+
}
37+
38+
// Driver program to test above functions
39+
public static void main(String args[])
40+
{
41+
String str = "One two three\n four\tfive ";
42+
System.out.println("No of words : " + countWords(str));
43+
}
44+
}

0 commit comments

Comments
 (0)