diff --git a/Others/CountWords.java b/Others/CountWords.java index c3e0ddf1..5dc63755 100644 --- a/Others/CountWords.java +++ b/Others/CountWords.java @@ -16,6 +16,7 @@ public class CountWords { String str = input.nextLine(); System.out.println("Your text has " + wordCount(str) + " word(s)"); + System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); input.close(); } @@ -25,4 +26,25 @@ public class CountWords { return s.trim().split("[\\s]+").length; } + /** + * counts the number of words in a sentence but ignores all potential + * non-alphanumeric characters that do not represent a word. runs in O(n) where + * n is the length of s + * + * @param s String: sentence with word(s) + * @return int: number of words + */ + private static int secondaryWordCount(String s) { + if (s == null || s.isEmpty()) + return 0; + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) { + if (Character.isLetter(c) || Character.isDigit(c)) + sb.append(c); + } + s = sb.toString(); + return s.trim().split("[\\s]+").length; + + } + }