File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ public static void main(String[] args) {
1616 String str = input .nextLine ();
1717
1818 System .out .println ("Your text has " + wordCount (str ) + " word(s)" );
19+ System .out .println ("Your text has " + secondaryWordCount (str ) + " word(s)" );
1920 input .close ();
2021 }
2122
@@ -25,4 +26,25 @@ private static int wordCount(String s) {
2526 return s .trim ().split ("[\\ s]+" ).length ;
2627 }
2728
29+ /**
30+ * counts the number of words in a sentence but ignores all potential
31+ * non-alphanumeric characters that do not represent a word. runs in O(n) where
32+ * n is the length of s
33+ *
34+ * @param s String: sentence with word(s)
35+ * @return int: number of words
36+ */
37+ private static int secondaryWordCount (String s ) {
38+ if (s == null || s .isEmpty ())
39+ return 0 ;
40+ StringBuilder sb = new StringBuilder ();
41+ for (char c : s .toCharArray ()) {
42+ if (Character .isLetter (c ) || Character .isDigit (c ))
43+ sb .append (c );
44+ }
45+ s = sb .toString ();
46+ return s .trim ().split ("[\\ s]+" ).length ;
47+
48+ }
49+
2850}
You can’t perform that action at this time.
0 commit comments