Site icon

Program to print duplicate characters in String (Java8 /Example)

Examples: Duplicate or repeated characters in a String (Java)

Example 1 : 
Input String = "ABCDAB"
The duplicate characters are A B
So, output of program should be A B

Example 2: 
Input String = "google rocks"
The duplicate characters are g and o
So, output of our program should be :g o

Algorithm to find duplicate characters in String (Java):

  1. User enter the input string.
  2. Convert input string to character buffer using String.toCharArray
  3. Create Set<Character> setDuplicateChars to hold repeated characters.
  4. Also, create Set<Character> setDistinctChars to hold unique characters.
  5. Loop through the character buffer and add characters to setDistinctChars.
  6. If value is already present in setDistinctChars then it’s duplicate chars.
    • Insert elements to setDistinctChars using add method of set class.
    • Use the property add method of set class to check duplicate characters
    • add method returns false if set already contain the specified element
  7. So, If insertion to  setDistinctChars returns false, then add repeated character to setDuplicateChars.

Add method of Set class to insert element:

Method Name Description
boolean add(E e) Adds the specified element to this set if it is not already present,if set already contains the element, the call leaves the set unchanged and returns false

Program: print duplicate characters of string in java

package org.learn;

import java.util.HashSet;
import java.util.Set;

public class DuplicateCharacters {

    public static final void duplicateChars(String input) {

        char []chInput = input.toCharArray();
        Set setDuplicated = new HashSet<>();
        Set distinctChars = new HashSet<>();

        for(char ch: chInput) {
            if(distinctChars.add(ch) == false)
                //if character is duplicated, then insert it into
                //duplicated set
                setDuplicated.add(ch);
        }

        //print duplicated characters
        System.out.print("Duplicate characters are: ");
        setDuplicated.forEach(ch -> System.out.print(ch + " "));
    }

    public static void main(String[] args) {
        String input = "ABCDAB";
        System.out.println("Input string is:"+input);
        duplicateChars(input);

        System.out.println("\n******************************");
        input = "google rocks";
        System.out.println("\nInput string is:"+input);
        duplicateChars(input);
    }
}

Output: print duplicate or repeated characters of string in java

Input string is:ABCDAB
Duplicate characters are: A B 

******************************

Input string is:google rocks
Duplicate characters are: g o
Exit mobile version