Skip to content

Commit 44921f2

Browse files
committed
Count the words
1 parent 00a78b3 commit 44921f2

1 file changed

Lines changed: 21 additions & 16 deletions

File tree

InterviewPrograms/src/com/java/strings/CountWords.java

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,45 +4,50 @@
44

55
/*
66
* Count the number of Words
7-
*
7+
* --------------------------
88
* Write the java program to count the number of
99
* words in the given string without string functions
1010
*
11+
* solution::
12+
* ----------
1113
* Count the number of white spaces " "
14+
*
15+
*
1216
* say Given String : java programming
1317
* no of words : 2
1418
* say Given String : code
1519
* no of words : 1
1620
*
1721
*/
22+
1823
public class CountWords {
1924
public static void main(String[] args) {
2025
Scanner scanner = new Scanner(System.in);
2126
System.out.println("Enter any String : ");
2227
String str = scanner.nextLine().trim();
28+
if(str.length() == 0){
29+
System.out.println("Number of wrods : 0");
30+
System.exit(0);
31+
}
2332
System.out.println("Number of words : "+countWords(str));
2433
scanner.close();
2534
}
2635

2736
private static int countWords(String str){
28-
int count = 0;
29-
boolean isWord = false;
37+
int count = 1;
3038
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'){
3342
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
3948
}
40-
}else{
41-
isWord = true;
4249
}
4350
}
44-
if(isWord == true)
45-
count++;
4651
return count;
4752
}
4853
}
@@ -51,12 +56,12 @@ private static int countWords(String str){
5156
Enter any String : java programming
5257
Number of words : 2
5358
54-
Enter any String : 123 123
59+
Enter any String : 123 123
5560
Number of words : 2
5661
5762
Enter any String : code
5863
Number of words : 1
5964
60-
Enter any String : I am a good coder
65+
Enter any String : I am a good coder
6166
Number of words : 5
6267
*/

0 commit comments

Comments
 (0)