Skip to main content

Posts

Showing posts with the label Grouping

Grouping Words With Their Counts in Java

In this article, we are going to know how to split the String input (a sentence or a paragraph) into words and count each words’ occurrences. Image by Author The picture above is our problem definition and let’s see how to do this in Java. String text = "We resolve to be brave. We resolve,,  to be good. We resolve to uphold the law according to our oath."; This is the paragraph or input. String textLower = text.toLowerCase(); textLower = textLower.replaceAll("\\W", " "); textLower = textLower.replaceAll("\\s+", " "); String[] words = textLower.split("\\s+"); Here, we have changed all letters to small letters using toLowerCase(). And then we replace characters apart from [a-zA-Z0–9_] with a space using replaceAll(“\\W”, “ ”). We can also replaceAll(“[^a-zA-Z0–9]”, “ ”).  Then we removed the spaces using replaceAll(“\\s+”, “ ”) and added a single space; this is to bypass the additional spaces and consecutive non-word characters ...