33import java .util .Scanner ;
44
55/**
6- * You enter a string into this program, and it will return how many words were
7- * in that particular string
8- *
96 * @author Marcus
107 */
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 () {
2310 }
2411
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 ) {
2618 if (s == null || s .isEmpty ()) {
2719 return 0 ;
2820 }
2921 return s .trim ().split ("[\\ s]+" ).length ;
3022 }
3123
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+
3234 /**
3335 * counts the number of words in a sentence but ignores all potential
3436 * non-alphanumeric characters that do not represent a word. runs in O(n)
@@ -37,17 +39,10 @@ private static int wordCount(String s) {
3739 * @param s String: sentence with word(s)
3840 * @return int: number of words
3941 */
40- private static int secondaryWordCount (String s ) {
41- if (s == null || s . isEmpty () ) {
42+ public static int secondaryWordCount (String s ) {
43+ if (s == null ) {
4244 return 0 ;
4345 }
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 ));
5247 }
5348}
0 commit comments