In this tutorial, we are sharing how to remove duplicate characters from String in Java.
For example, if given String is “aaaaaa” then output should be “a”, because rest of the “a” are duplicates. Similarly, if the input is “abcd” then output should also be “abcd” because there is no duplicate character in this String.
Copy the below program and executive it to see the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.*; class freewebmentor { static String removeDuplicate(char str[], int n) { // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } return String.valueOf(Arrays.copyOf(str, index)); } // Driver code public static void main(String[] args) { char str[] = "aaaaaa".toCharArray(); int n = str.length; System.out.println(removeDuplicate(str, n)); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.