Java – how to replace duplicated characters in a string? [closed]

Check out below code:

public class Test {
    public static void main(String[] args) {
        String str = "aacbbbz";
        Map<Character, Integer> items = new HashMap<Character, Integer>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (items.containsKey(c)) {
                int cnt = items.get(c);
                items.put(c, ++cnt);
            } else {
                items.put(c, 1);
            }
        }

        Set<Character> keys = items.keySet();
        for (Character ch : keys) {
            if (items.get(ch) > 1) {
                str = str.replaceAll(ch.toString(), "*");
            }
        }

        System.out.println("Output : " + str);
    }
}

Output is
Output : **c***z

Browse More Popular Posts

Leave a Comment