4
4
5
5
/*
6
6
* Count the number of Words
7
- *
7
+ * --------------------------
8
8
* Write the java program to count the number of
9
9
* words in the given string without string functions
10
10
*
11
+ * solution::
12
+ * ----------
11
13
* Count the number of white spaces " "
14
+ *
15
+ *
12
16
* say Given String : java programming
13
17
* no of words : 2
14
18
* say Given String : code
15
19
* no of words : 1
16
20
*
17
21
*/
22
+
18
23
public class CountWords {
19
24
public static void main (String [] args ) {
20
25
Scanner scanner = new Scanner (System .in );
21
26
System .out .println ("Enter any String : " );
22
27
String str = scanner .nextLine ().trim ();
28
+ if (str .length () == 0 ){
29
+ System .out .println ("Number of wrods : 0" );
30
+ System .exit (0 );
31
+ }
23
32
System .out .println ("Number of words : " +countWords (str ));
24
33
scanner .close ();
25
34
}
26
35
27
36
private static int countWords (String str ){
28
- int count = 0 ;
29
- boolean isWord = false ;
37
+ int count = 1 ;
30
38
for (int i =0 ;i <str .length ();i ++){
31
- String ch = str .charAt (i )+"" ;
32
- if (ch .equals (" " )){
39
+ char ch = str .charAt (i );
40
+ System .out .println (ch );
41
+ if (ch == ' ' || ch == '\t' || ch == '\n' ){
33
42
count ++;
34
- isWord = false ;
35
- //this while loop removes continuous
36
- //white spaces
37
- while ( ch . equals ( " " )){
38
- ch = str . charAt ( i ++)+ "" ;
43
+ ch = str . charAt ( i + 1 ) ;
44
+ while ( ch == ' ' || ch == '\t' || ch == '\n' ){
45
+ i ++;
46
+ ch = str . charAt ( i + 1 );
47
+ //this while loop removes continuous white spaces
39
48
}
40
- }else {
41
- isWord = true ;
42
49
}
43
50
}
44
- if (isWord == true )
45
- count ++;
46
51
return count ;
47
52
}
48
53
}
@@ -51,12 +56,12 @@ private static int countWords(String str){
51
56
Enter any String : java programming
52
57
Number of words : 2
53
58
54
- Enter any String : 123123
59
+ Enter any String : 123123
55
60
Number of words : 2
56
61
57
62
Enter any String : code
58
63
Number of words : 1
59
64
60
- Enter any String : I am a good coder
65
+ Enter any String : I am a good coder
61
66
Number of words : 5
62
67
*/
0 commit comments