Remove duplicate characters in a String Java



 Write a program that removes the duplicate characters from the given string.

Java Program to Remove duplicate characters

public final class Strings {

    public static String removeDuplicates(String str) {

        char[] chArray = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char ch : chArray) {
            if (sb.indexOf(String.valueOf(ch)) == -1) {
                sb.append(ch);
            }
        }

        return sb.toString();
    }
}

Test

public class Main {

    private static final String TEXT = "!ABCBA;C D E-D  D  DFA;";

    public static void main(String[] args) {

        System.out.println("Input text: \n" + TEXT + "\n");
        String resultV1 = Strings.removeDuplicates(TEXT);
        System.out.println("String with no duplicates: \n" + resultV1);
    }
}

Output:

Input text: 
!ABCBA;C D E-D  D  DFA;

String with no duplicates: 
!ABC; DE-F

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments