forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountChar.java
44 lines (33 loc) · 966 Bytes
/
CountChar.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
37
38
39
40
41
42
43
44
package Others;
import java.util.Scanner;
/**
* @author Kyler Smith, 2017
* <p>
* Implementation of a character count.
* (Slow, could be improved upon, effectively O(n).
*/
public class CountChar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your text: ");
String str = input.nextLine();
input.close();
System.out.println("There are " + CountCharacters(str) + " characters.");
}
/**
* @param str: String to count the characters
* @return int: Number of characters in the passed string
*/
private static int CountCharacters(String str) {
int count = 0;
if (str == "" || str == null) {
return 0;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isWhitespace(str.charAt(i))) {
count++;
}
}
return count;
}
}