Java Program To Remove Repeated Characters In A String
Chapter:
String Handling
Last Updated:
15-08-2023 14:16:20 UTC
Program:
/* ............... START ............... */
public class RemoveRepeatedCharacters {
public static void main(String[] args) {
String input = "programming";
String result = removeRepeatedCharacters(input);
System.out.println("Original String: " + input);
System.out.println("String after removing repeated characters: " + result);
}
public static String removeRepeatedCharacters(String str) {
StringBuilder result = new StringBuilder();
boolean[] visited = new boolean[256]; // Assuming ASCII characters
for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);
if (!visited[currentChar]) {
result.append(currentChar);
visited[currentChar] = true;
}
}
return result.toString();
}
}
/* ............... END ............... */
Output
Original String: programming
String after removing repeated characters: progamin
In this example, the input string is "programming", and the output string after removing
repeated characters is "progamin". The repeated characters "r" and "m" have been removed,
resulting in the modified string.
Notes:
-
The removeRepeatedCharacters method is defined to achieve the removal of repeated characters.
- The method uses a StringBuilder named result to store the characters without repetitions.It also uses a boolean array visited to keep track of characters that have been encountered.
- The loop iterates through each character in the input string.
- For each character:
- It checks if the character has not been encountered before by looking up the visited array.
- If the character is not visited, it appends the character to the result StringBuilder and marks it as visited.
- After processing all characters, the method returns the modified string without repeated characters.
- In summary, the program takes advantage of a boolean array to keep track of characters already encountered and utilizes a StringBuilder to create a new string with repeated characters removed.
Tags
Java program to remove repeated characters in a string #Remove duplicate characters in a string Java using HashMap #Java Program To Remove Duplicates From String