Duplicate characters in a string are characters that appear multiple times. These characters can be found using a nested loop or some other ways
Java program to find all duplicate characters in a string
public class DuplicateCharacter { public static void main(String arg[]) { String originalstring = "Java Proedu Questions"; char[] originalCharArray = originalstring.toCharArray(); System.out.println("The string is:" + originalstring); System.out.print("Duplicate Characters in string are: "); for (int i = 0; i < originalstring.length(); i++) { for (int j = i + 1; j < originalstring.length(); j++) { if (originalCharArray[i] == originalCharArray[j]) { System.out.print(originalCharArray[j] + " "); break; } } } } }
Output
The string is:Java Proedu Questions Duplicate Characters in string are: a o e u s
Java program to find all duplicate characters in a string using another way
public class DuplicateCharacter { public static void main(String[] args) { String originalString = "Java Proedu Questions"; int count; char originalChar[] = originalString.toCharArray(); System.out.println("Duplicate characters in a given string: "); for (int i = 0; i < originalChar.length; i++) { count = 1; for (int j = i + 1; j < originalChar.length; j++) { if (originalChar[i] == originalChar[j] && originalChar[i] != ' ') { count++; // Set string[j] to 0 to avoid printing visited character originalChar[j] = '0'; } } if (count > 1 && originalChar[i] != '0') System.out.print(originalChar[i]+" "); } } }
Output
Duplicate characters in a given string: a o e u s