1. Introduction
In Java, strings are sequences of characters. Sometimes, we encounter situations where we need to remove duplicate characters from a string. This program will demonstrate how to achieve this in Java using a StringBuilder and a HashSet.
2. Program Steps
1. Define the main method, which is the entry point to the program.
2. Declare and initialize the input string.
3. Create an empty StringBuilder object to hold the result.
4. Create a HashSet to store unique characters encountered.
5. Iterate through each character in the input string.
6. If the character is not in the HashSet, append it to the StringBuilder and add it to the HashSet.
7. Convert the StringBuilder to a string and print the result.
3. Code Program
public class RemoveDuplicates {
public static void main(String[] args) {
// Step 2: Declare and initialize the input string
String input = "programming";
// Step 3: Create an empty StringBuilder object to hold the result
StringBuilder result = new StringBuilder();
// Step 4: Create a HashSet to store unique characters encountered
Set<Character> uniqueChars = new HashSet<>();
// Step 5: Iterate through each character in the input string
for (char c : input.toCharArray()) {
// Step 6: If the character is not in the HashSet, append it to the StringBuilder and add it to the HashSet
if (uniqueChars.add(c)) {
result.append(c);
}
}
// Step 7: Convert the StringBuilder to a string and print the result
System.out.println("Input String: " + input);
System.out.println("String with duplicates removed: " + result.toString());
}
}
Output:
Input String: programming String with duplicates removed: progam
4. Step By Step Explanation
– Step 1: The main method is defined as the program’s entry point.
– Step 2: The input string input is declared and initialized with the value "programming".
– Step 3: An empty StringBuilder object result is created to build the final string.
– Step 4: A HashSet named uniqueChars is created to store unique characters encountered while iterating through the string.
– Steps 5 and 6: We iterate through each character in the input string. If the character is not already in the HashSet, it is appended to the StringBuilder and added to the HashSet.
– Step 7: The StringBuilder is converted to a string and printed as the final output along with the original input string.