Java Program to find duplicate characters in a String
FindDuplicate.java
/* Code From Learnoset - Learn Coding Online.*/
/* Download Learnoset App from PlayStore to learn coding,
* projects
*/
// Java Program to find duplicate characters in a String
public class FindDuplicate {
public void countDupChars(String str) {
// here all the checked characters will come
String checkedChar = "";
// get all characters available in 'str'
for (int i = 0; i < str.length(); i++) {
// get character at 'i' position
char getCharacter = str.charAt(i);
/* check if that character is available in 'checkedChar'
* if available it means that character is already checked before no need to check again*/
if (checkedChar.indexOf(getCharacter) == -1) {
int duplicateCount = 0;
// add character to 'checkedChar' to prevent re-checking of this character again
checkedChar = checkedChar + getCharacter;
/* compare getCharacter's value to all other characters available in 'str'
* If getCharacter's value matches with any character str then increament duplicateCount's value
*/
for (int v = 0; v < str.length(); v++) {
// check if not not same position as getCharacter's position
if (i != v) {
/* check if character at 'v' position is matching with 'getCharacter'
* if matching then increament duplicateCount's value
*/
if (str.charAt(v) == getCharacter) {
duplicateCount++;
}
}
}
// if duplicates available of 'getCharacter' then display them
if (duplicateCount != 0) {
System.out.println(duplicateCount + " duplicate found of '" + getCharacter + "'");
}
}
}
}
public static void main(String a[]) {
// create an object of FindDuplicate class to call countDupChars() function in it
FindDuplicate obj = new FindDuplicate();
// print on screen
System.out.println("String: learnoset");
System.out.println("Duplicate Characters in learnoset");
// calling function countDupChars() to check duplicate
obj.countDupChars("learnoset");
// print on screen
System.out.println("\nString: programming");
System.out.println("Duplicate Characters in programming");
// calling function countDupChars() to check duplicate
obj.countDupChars("programming");
}
}
Projects with Source Code + Video Tutorials
You can download our Java and Android Studio Projects with Source Code and Video Tutorials.
Modern Splash Screen with Animations - 01
Online Tic Tac Toe game Using Firebase Database in Android Studio
Firebase Push Notifications | Background Notification
If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com
Follow us to learn Coding and get in touch with new Technologies.
