Java Program to count the occurrence of duplicate characters in String

Java Program to count the occurrence of duplicate characters in String

In this tutorial, we will be learning the writing a java program to count the duplicate characters in the string. Basically, for a given string we have to print all duplicate characters with their occurrence.

For example:

Suppose the String input given by the user are : TutorialWorldTutorial

So the output should be

T = 2
u = 2
t = 2
o = 3
r = 3
i = 2
a = 2
l = 3

Program 1: Java Program to count the occurrence of duplicate characters in String

[java]
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print(“Please enter a string: “);
String str= sc.nextLine();
int count, douplicateCount = 0;
char strArr[] = str.toCharArray();
System.out.println(“Occurrence of the Duplicate characters in string: “);
for(int i = 0; i < strArr.length; i++) {
count = 1;
for(int j = i+1; j <strArr.length; j++) {
if(strArr[i] == strArr[j] && strArr[i] != ‘ ‘) {
count++;
douplicateCount++;
strArr[j] = ‘0’;
}
}
if(count > 1 && strArr[i] != ‘0’)
System.out.println(strArr[i]+” = “+count);
count = 1;
}
}
}
[/java]

Output

java program count the occurrence of duplicate characters in String