Tuesday, 5 February 2019

4.How to remove duplicate Characters from a String in java.


Description:
Write a sample code to remove duplicate Characters from a String.

Code:
?
1
2
3
4
5
6
7
8
9
10

import java.util.HashSet;
import java.util.Set;

public class RemoveDuplicate {
public static void main(String[] args) {
String str = "godblessgovind";
char[] characters = str.toCharArray();
Set set = new HashSet();
StringBuilder sb = new StringBuilder();
System.out.println("String with duplicates : " + str);
for (char c : characters) {
if (!set.contains(c)) {
set.add(c);
sb.append(c);
}
}
System.out.println("String after duplicates removed : " + sb.toString());
}
}

Output:
String with duplicates : godblessgovind
String after duplicates removed : godblesvin

No comments:

Post a Comment