The program prints repeated words with number of occurrences in a given string using Map or without Map. It first creates an array from given string using split method and then after considers as any word duplicate if a word come atleast two times. For example, “blue sky and blue ocean” in this blue is repeating word with 2 times occurrence.
In this article, there are two ways used to achieve the solution, using Map and using String Array.
Program:
class DuplicateWordsWithoutUsingMap { public static void main(String[] args) { String str = " this is is the word this is this"; int count; String duplicates = ""; String[] words = str.toLowerCase().trim().split(" "); for (int i = 0; i < words.length; i++) { count = 1; for (int j = i + 1; j < words.length; j++) { if (words[i].equals(words[j])) { count++; } } if (count > 1) { if (duplicates.isEmpty()) { duplicates += " " + words[i] + " : " + count; } else if (!duplicates.matches("(.*) " + words[i] + " (.*)")) { duplicates += " " + words[i] + " : " + count; } } } System.out.println(duplicates); } }
Output:
Program:
class DuplicateWords { public static void main(String[] args) { String str = "This is a program to find duplicate words in a string, again! a program"; String[] words = str.toLowerCase().trim().split(" "); Map<String, Integer> duplicateString = new HashMap<>(); int count = 1; for (String x : words) { if (duplicateString.containsKey(x)) { duplicateString.put(x, duplicateString.get(x) + 1); } else { duplicateString.put(x, count); } } System.out.println("Duplicate Words in a String : "); for (Map.Entry a : duplicateString.entrySet()) { int val = (Integer) a.getValue(); if (val > 1) { System.out.println(a); } } } }
Output:
Duplicate Words in a String : a=3 program=2
This post was last modified on December 27, 2020