3
3
import java .util .Scanner ;
4
4
5
5
/**
6
- * You enter a string into this program, and it will return how many words were
7
- * in that particular string
8
- *
9
6
* @author Marcus
10
7
*/
11
- public class CountWords {
12
-
13
- public static void main (String [] args ) {
14
- Scanner input = new Scanner (System .in );
15
- System .out .println ("Enter your text: " );
16
- String str = input .nextLine ();
17
-
18
- System .out .println ("Your text has " + wordCount (str ) + " word(s)" );
19
- System .out .println (
20
- "Your text has " + secondaryWordCount (str ) + " word(s)"
21
- );
22
- input .close ();
8
+ final public class CountWords {
9
+ private CountWords () {
23
10
}
24
11
25
- private static int wordCount (String s ) {
12
+ /**
13
+ * @brief counts the number of words in the input string
14
+ * @param s the input string
15
+ * @return the number of words in the input string
16
+ */
17
+ public static int wordCount (String s ) {
26
18
if (s == null || s .isEmpty ()) {
27
19
return 0 ;
28
20
}
29
21
return s .trim ().split ("[\\ s]+" ).length ;
30
22
}
31
23
24
+ private static String removeSpecialCharacters (String s ) {
25
+ StringBuilder sb = new StringBuilder ();
26
+ for (char c : s .toCharArray ()) {
27
+ if (Character .isLetterOrDigit (c ) || Character .isWhitespace (c )) {
28
+ sb .append (c );
29
+ }
30
+ }
31
+ return sb .toString ();
32
+ }
33
+
32
34
/**
33
35
* counts the number of words in a sentence but ignores all potential
34
36
* non-alphanumeric characters that do not represent a word. runs in O(n)
@@ -37,17 +39,10 @@ private static int wordCount(String s) {
37
39
* @param s String: sentence with word(s)
38
40
* @return int: number of words
39
41
*/
40
- private static int secondaryWordCount (String s ) {
41
- if (s == null || s . isEmpty () ) {
42
+ public static int secondaryWordCount (String s ) {
43
+ if (s == null ) {
42
44
return 0 ;
43
45
}
44
- StringBuilder sb = new StringBuilder ();
45
- for (char c : s .toCharArray ()) {
46
- if (Character .isLetter (c ) || Character .isDigit (c )) {
47
- sb .append (c );
48
- }
49
- }
50
- s = sb .toString ();
51
- return s .trim ().split ("[\\ s]+" ).length ;
46
+ return wordCount (removeSpecialCharacters (s ));
52
47
}
53
48
}
0 commit comments