File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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\t five " ;
42+ System .out .println ("No of words : " + countWords (str ));
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments