Java Program to find duplicate characters count in a string - The Coding Shala

Home >> Java Programs >> Find duplicate characters count in a string

 In this post, we will learn how to find duplicate characters count in a string and will write a Java program to find duplicate characters and their count.

Java Program to find duplicate characters count in a String

Problem

A string is given, you have to find all the duplicate characters in the string and need to return their count.

Example 1

Input: "aabb"
Output: a 2
             b 2

Approach 1

We need to count the occurrence of each character in the given string. If the count is more than 1(one) then it's a duplicate character and we need to return that.

Java Program: 

import java.util.*;

class Main {
		
	public static void duplicate(String str) {
		 int[] arr = new int[26];   
										
		 for(int i=0; i<str.length(); i++) {
			int index = str.charAt(i) - 'a';
			arr[index] = arr[index]+1;
		 }
		 
		 for(int i=0; i<26; i++){
			if(arr[i] > 1){
				char c = (char)(i + 'a');
				System.out.println("duplicate char "+c+" count is "+arr[i]); 
			}
		 }
		 
		}
	
	public static void main(String[] args) {
			String s1 = "abcdaefghccabcda";
			duplicate(s1);
		}
	}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala