Java Program to remove duplicate char from String,

package RemoveDuplicaeCharFromSttring;

import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateCharFromString {
public static String removeDuplicateCharsFromSring(String inputSring) {
if (inputSring == null || inputSring.isEmpty()) {
return inputSring;
}
// A LinkedHashSet stores unique characters and maintains insertion order.
Set<Character> seen = new LinkedHashSet<>();
// Use a StringBuilder for efficient string building.
StringBuilder result = new StringBuilder();
// Iterate through the input string
for (char ch : inputSring.toCharArray()) {
// If the character is not already in the set, add it to both the set and the result string
if (seen.add(ch)) {
result.append(ch);
}
}
// Convert the StringBuilder to a String and return
return result.toString();
}
public static void main(String[] args) {
String input1 = "programming";
String output1 = removeDuplicateCharsFromSring(input1);
System.out.println("Original String: " + input1);
System.out.println("After removing dulicate chars: " + output1);
}
}

Comments

Popular posts from this blog

GenAI in QA Automation: Game Changer or Just Hype?

How to choose the right QA Automation tool for your web application?

How to validate broken link on the webpage using playwright?