Remove duplicate characters in a string
- We can remove duplicates characters from a given string using for loops, HashSet, indexOf() method.
import java.util.*;
public class removeDuplicatesFromString {
public static void main(String[] args) {
String str = "cbacdcbc3";
String uniqueString = "";
for (int i = 0; i <= str.length() - 1; i++) {
char c = str.charAt(i);
if (uniqueString.indexOf(c) < 0) {
uniqueString = uniqueString + c;
}
}
System.out.println("Remove duplicates using indexOf()=" + uniqueString);
System.out.println("<<----------------------------------->>");
Set<Character> s = new HashSet<>();
for (int i = 0; i <= str.length() - 1; i++) {
s.add(str.charAt(i));
}
String str1 = "";
for (char c : s) {
str1 = str1 + c;
}
System.out.println("Remove duplicates using HashSet=" + str1);
System.out.println("<<----------------------------------->>");
String distinct = "";
for (int i = 0; i <= str.length() - 1; i++) {
if (!distinct.contains(String.valueOf(str.charAt(i)))) {
distinct += String.valueOf(str.charAt(i));
}
}
System.out.println("Remove duplicates using for loop()=" + distinct);
}
}
Output:
Remove duplicate characters from string in java |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.