Duplicate characters with count from string using loop
Following is the logic:
- Take one character from string.
- Compare this character with other characters of the string.
- If character is found then this is a duplicate character and increase counter of that character.
- Remove this character from string so that it is not picked in next iteration.
public class DuplicateCharsWithCount { public static void main(String[] args) { findDuplicateCharsWithCount("Hello from Learnitweb"); } private static void findDuplicateCharsWithCount(String str) { int count; for (int i = 0; i < str.length(); i++) { count = 1; // Take one char at a time char c = str.charAt(i); // Don't count spaces if (c == ' ') continue; for (int j = i + 1; j < str.length(); j++) { if (c == str.charAt(j)) { count++; // remove the char so that it is not picked again in next iteration str = str.substring(0, j) + str.substring(j + 1); } } if (count > 1) { System.out.println(c + ":" + count); } } } }
Output
e:3
l:2
o:2
r:2
Duplicate characters with count from string using map
Following is the logic:
- Create character array from string.
- Create a empty map.
- Loop array and take one character at a time. Check for each character in map.
- Check if the character is found as key in map. If character is not found then put character as key in map and value as 1.
- If character is found then increase value of the key(character) by 1.
import java.util.HashMap; import java.util.Map; public class DuplicateCharsWithCount { public static void main(String[] args) { String str = "Hello from Learnitweb"; char[] chars = str.toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (char c : chars) { if (map.containsKey(c)) { int counter = map.get(c); map.put(c, ++counter); } else { map.put(c, 1); } } System.out.println("Duplicate characters:"); for (char c : map.keySet()) { if (map.get(c) > 1) { //Do not print space if(c != ' ') { System.out.println(c + ":" + map.get(c)); } } } } }
Output
e:3
l:2
o:2
r:2