-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcountCharWord.java
36 lines (31 loc) · 957 Bytes
/
countCharWord.java
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
import java.util.Scanner;
public class countCharWord {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
String str;
System.out.print("Enter a String : ");
str = s.nextLine();
System.out.println("Total Number of Word: " + countWords(str));
System.out.println("The Number of Character: " + countChar(str));
}
public static int countWords(String str) {
int count = 1;
for (int i = 0; i <= str.length() - 1; i++) {
if (str.charAt(i) == ' ' && str.charAt(i + 1) != ' ') {
count++;
}
}
return count;
}
public static int countChar(String str) {
int count = 1;
for (int i = 0; i < str.length() - 1; i++) {
count++;
if (!(str.charAt(i) == ' ')) {
} else {
count -= 1;
}
}
return count;
}
}