4
import java.util.*;
public class DuplicateCharacters {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
        System.out.println("Enter String: ");
        String str = s.nextLine();

        for(int i=0;i<str.length()-1;i++)
        {
            for(int j=i+1;j<str.length();j++)

            {
            if(str.charAt(i)==str.charAt(j))
            {

                System.out.print(str.charAt(j));
            }
            }
        }
    }

}

My code works for string contains 2 duplicate character only ..

e.g. suppose input= india it prints i but when input aaa , output = a a a..it should print a once only

1
  • I have it using set.. i need it using string only so Commented Feb 15, 2017 at 4:20

10 Answers 10

2

Attempt to put every newly read character into a Set<Character>. If adding to the set returns false, then add it to a set tracking all repeat characters. Here's pseudocode for it:

Set<Character> uniqueChars = new HashSet<Character>();
Set<Character> repeats = new HashSet<Character>();
for(int i = 0; i < str.length() - 1; i++) {
    if (!uniqueChars.add(str.charAt(i)) {
        repeats.add(str.charAt(i));
    }
}

// now loop through the repeats set and print out each one.
Sign up to request clarification or add additional context in comments.

Comments

2

If you can use a third-party library, the following will work using Eclipse Collections:

String str = "india";
MutableCharSet dupes = Strings.asChars(str).toBag().selectDuplicates().toSet();
System.out.println(dupes.makeString(""));  // outputs i

The Strings class, will return a CharAdapter from the call to asChars. The toBag method will return a MutableCharBag, which has all the char values in the String with their corresponding counts. The selectDuplicates method will return another MutableCharBag with only the char values that have more than one occurrence. The toSet method returns a MutableCharSet, which will have the unique char values that had duplicates. The makeString("") method will return a String of the chars stored in the MutableCharSet with no separator between them.

Note: I am a committer for Eclipse Collections.

Comments

2
import java.util.*;

public class DuplicateCharacters {

    static final int NO_OF_CHARS = 256;

    public static void main(String[] args) {

       Scanner s = new Scanner(System.in);
       System.out.println("Enter String: ");
       String str = s.nextLine();
       int count[] = new int[NO_OF_CHARS];

       for(int i=0;i<str.length();i++)
       {
          count[str.charAt(i)]++;
       }
       for (int i = 0; i < NO_OF_CHARS; i++) 
          if(count[i] > 1) 
             System.out.printf("%c", i);
      }
   }

1 Comment

Code-only answers are discouraged. Please click on edit and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answer/answers. Thanks
1

I would start by decomposing the problem into two parts. First, you need a method to count the number of occurrences of a given character from a given start index. That might look something like,

static int countFrom(String str, char ch, int start) {
    int count = 0;
    for (int i = start; i < str.length(); i++) {
        if (str.charAt(i) == ch) {
            count++;
        }
    }
    return count;
}

Then you can use that with a Set<Character> (to track which characters you have already used) like

Scanner s = new Scanner(System.in);
System.out.println("Enter String: ");
String str = s.nextLine();
Set<Character> set = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (!set.contains(ch)) {
        int count = countFrom(str, ch, i);
        if (count > 1) {
            System.out.print(ch);
        }
        set.add(ch);
    }
}
System.out.println();

and without a Set, you can emulate one with a String like

String setString = "";
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (!setString.contains(String.valueOf(ch))) {
        int count = countFrom(str, ch, i);
        if (count > 1) {
            System.out.print(ch);
        }
        setString += ch;
    }
}

1 Comment

@shraddha if it works for you mark as accepted answer so question be removed from unanswer question list :)
1

This is another way to solve it..

    Scanner s = new Scanner(System.in);
    System.out.println("Enter String: ");
    String str = s.nextLine();

    String duplicates = "";

    for (int i = 0; i < str.length() - 1; i++) {
        for (int j = i + 1; j < str.length(); j++)

        {
            if (str.charAt(i) == str.charAt(j)) {

                if (!duplicates.contains(String.valueOf(str.charAt(j)))) {
                    duplicates += str.charAt(j);
                    break;
                }

            }
        }
    }

    System.out.println(duplicates);

Comments

1

Convert String in char array and append it to String builder and check if String builder Already contains that char then print that duplicate char.

public static void findduplicate(String word) {

        char arr[] = word.toCharArray();
        StringBuilder s = new StringBuilder();
        for (char c : arr) {
            int index = s.indexOf("" + c);
            if (index != -1) {
                System.out.println("duplicate character "+c);
            } else {
                s.append(c);
            }
        }

    }

1 Comment

Adding explanation to your answer will help users
0

Or consider a Map

    String word = "aiaiiab";
    Map <Character, Integer> charMap = new HashMap<Character, Integer> ();
    for (char c : word.toCharArray()) {
        Integer count = charMap.get(new Character(c));
        if (count == null) {
            charMap.put(new Character(c), 1);
        }
        else {
            charMap.put(new Character(c), count.intValue() + 1);
        }
    }

    for (Entry<Character, Integer> obj : charMap.entrySet()) {

        if (obj.getValue() > 1) {
            System.out.println(obj.getKey());
        }
    }

Comments

0
package com.java2novice.algos;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DuplicateCharsInString {

public void findDuplicateChars(String str){

    Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
    char[] chrs = str.toCharArray();
    for(Character ch:chrs){
        if(dupMap.containsKey(ch)){
            dupMap.put(ch, dupMap.get(ch)+1);
        } else {
            dupMap.put(ch, 1);
        }
    }
    Set<Character> keys = dupMap.keySet();
    for(Character ch:keys){
        if(dupMap.get(ch) > 1){
            System.out.println(ch+"--->"+dupMap.get(ch));
        }
    }
}

public static void main(String a[]){
    DuplicateCharsInString dcs = new DuplicateCharsInString();
    dcs.findDuplicateChars("Java2Novice");
}
}

Comments

0
public class GFG  
{ 
  static final int NO_OF_CHARS = 256; 

  /* Fills count array with frequency of characters */
  static void fillCharCounts(String str, int[] count) 
  { 
    for (int i = 0; i < str.length();  i++) 
      count[str.charAt(i)]++; 
  } 

  /* Print duplicates present in the passed string */
  static void printDups(String str) 
  { 
    // Create an array of size 256 and fill count of every character in it 
    int count[] = new int[NO_OF_CHARS]; 
    fillCharCounts(str, count); 

    for (int i = 0; i < NO_OF_CHARS; i++) 
      if(count[i] > 1) 
        System.out.printf("%c,  count = %d \n", i,  count[i]); 
  } 

  // Driver Method 
  public static void main(String[] args) 
  { 
    String str = "test string"; 
    printDups(str); 
  } 
} 

1 Comment

Hi, welcome to stackoverflow. It's better if you can add some explanation to your answer. Code-only answers are not that much of a help.
0
    String abc = "22533"; // Initialize String variable
    int cnt = 0; // declaring integer variable with value as 0
    char[] inp = str.toCharArray(); // converts the given string into a sequence of characters

    System.out.println("Duplicate Characters are:");
    for (int i = 0; i < str.length(); i++) { // This loop starts with first character of the given String
        for (int j = i + 1; j < str.length(); j++) { // This loop starts with second character of the given string
            if (inp[i] == inp[j]) { // Comparing first loop index value with second loop index value of inp character array.
                System.out.println(inp[j]); // If value matches, it will print result.
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.