Friday, 18 December 2015

Java program to find duplicate character in the string

Requirement: When I run the Java program, it should ask me to enter a string value. And as an output it should display the duplicate character in the supplied string (say if the supplied string value is susanto it should give the output as s).

Solution: The Java program for the above requirement is shown below:

Program 1:

package com.susanto;

import java.io.IOException;
import java.util.Scanner;

public class DuplicateCharacter {

       public static void main(String[] args) throws IOException {
             Scanner sc = new Scanner(System.in);
             System.out.print("Enter the string : ");
             String ch = sc.nextLine();
             int count = 0, len = 0;
             do {
                    try {
                           char name[] = ch.toCharArray();
                           len = name.length;
                           count = 0;
                           for (int j = 0; j < len; j++) {
                                 if ((name[0] == name[j]))
                                        count++;
                           }
                           if (count > 1)
                                 System.out.println("Duplicate character is : " + name[0]);
                           ch = ch.replace("" + name[0], "");
                    } catch (Exception ex) {
                    }
             } while (len != 1);
       }
}
Output:

Enter the string : susanto
Duplicate character is : s
 
 
 

Thanks & Regards,
Susanto Paul