Skip to content

Commit da55838

Browse files
KylerSmithKylerSmith
KylerSmith
authored and
KylerSmith
committed
Count character algo added
1 parent ad1e42c commit da55838

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

CountChar.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.Scanner;
2+
3+
4+
/**
5+
* @author Kyler Smith, 2017
6+
*
7+
* Implementation of a character count.
8+
* (Slow, could be improved upon, effectively O(n).
9+
* */
10+
11+
public class CountChar {
12+
13+
public static void main(String[] args) {
14+
Scanner input = new Scanner(System.in);
15+
System.out.print("Enter your text: ");
16+
String str = input.nextLine();
17+
18+
System.out.println("There are " + CountCharacters(str) + " characters.");
19+
}
20+
21+
22+
23+
/**
24+
* @param str: String to count the characters
25+
*
26+
* @return int: Number of characters in the passed string
27+
* */
28+
29+
public static int CountCharacters(String str) {
30+
31+
int count = 0;
32+
33+
if(str.isEmpty() || str == null)
34+
return -1;
35+
36+
for(int i = 0; i < str.length(); i++)
37+
if(!Character.isWhitespace(str.charAt(i)))
38+
count++;
39+
40+
return count;
41+
}
42+
}

0 commit comments

Comments
 (0)