Skip to content

Commit 4ddbaca

Browse files
committed
secondaryWordCount method added
1 parent a4156fc commit 4ddbaca

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Others/CountWords.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)