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) {
16
16
String str = input .nextLine ();
17
17
18
18
System .out .println ("Your text has " + wordCount (str ) + " word(s)" );
19
+ System .out .println ("Your text has " + secondaryWordCount (str ) + " word(s)" );
19
20
input .close ();
20
21
}
21
22
@@ -25,4 +26,25 @@ private static int wordCount(String s) {
25
26
return s .trim ().split ("[\\ s]+" ).length ;
26
27
}
27
28
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
+
28
50
}
You can’t perform that action at this time.
0 commit comments