Print Duplicate Characters in String Using Java

Programming is always a fun and creative task. The more creative you can think the better programmer you will become. However, programming isn’t always about solving problems sometimes there’s also a fun aspect to it which makes it way more satisfying. If you are a programmer then you might have already played with strings multiple Times. So today we are going to show you a cool program. With the help of this program, you will be able to print duplicate characters in a string using java language.

 

So open up your IDE and let’s get started real quick. 😎😎. Once you understand the logic practice this program on your own to make your brain work in problem-solving way.

 

What’s The Approach?

 

We will follow the basic approach of using for loop to find similar characters in a string using Java. There will be two loops.

 

The outer loop will select the character to be found for duplication in a string.

 

However, in the inner loop, we will find if a character gets repeated, eventually giving us our desired output. 

 

Java Program To Print Duplicate Characters in String

 

Input: Tech Decode Tutorials

 

public class TechDecodeTutorials {  

     public static void main(String[] args) {  

        String string1 = "Tech  Decode Tutorials";  
        int count;  
          
        //Converts given string into character array  
        char string[] = string1.toCharArray();  
          
        System.out.println("Duplicate characters in a given string: ");  
        //Counts each character present in the string  
        for(int i = 0; i <string.length; i++) {  
            count = 1; 
 
            for(int j = i+1; j <string.length; j++) {  
                if(string[i] == string[j] && string[i] != ' ') {  
                    count++;  
                    //Set string[j] to 0 to avoid printing visited character  
                    string[j] = '0';  
                }  
            } 
 
            //A character is considered as duplicate if count is greater than 1  
            if(count > 1 && string[i] != '0')  
                System.out.println(string[i]);  
        }  
    }  
}

 

Output:

 

Duplicate characters in a given string: 
T
e
c
o

Also Read: How To Print Hello World in Java Without Semicolon

 

Wanna know more about strings in Java then read this Java String.From Javatpoint

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *