w3resource

Java: Remove duplicate characters from a given string presents in another given string


41. Remove Duplicates Using Mask String

Write a Java program to remove duplicate characters from a given string that appear in another given string.

Visual Presentation:

Java String Exercises: Remove duplicate characters from a given string presents in another given string


Sample Solution:

Java Code:

// Importing necessary Java utilities.
import java.util.*;

// Define a class named Main.
public class Main {
    
    // Main method to execute the program.
    public static void main(String[] args) {
        // Define two strings.
        String str1 = "the quick brown fox";
        String str2 = "queen";
        
        // Print the given strings.
        System.out.println("The given string is: " + str1);
        System.out.println("The given mask string is: " + str2);
        
        // Create a character array of the length of the first string.
        char arr[] = new char[str1.length()];
        
        // Create a character array to represent a mask of size 256 (ASCII characters).
        char[] mask = new char[256];
        
        // Loop through the characters of the mask string and count occurrences of each character.
        for (int i = 0; i < str2.length(); i++)
            mask[str2.charAt(i)]++;
        
        // Print a header for the new string.
        System.out.println("\nThe new string is: ");
        
        // Loop through the characters of the first string.
        for (int i = 0; i < str1.length(); i++) {
            // If the character at the current index in str1 is not found in str2 (mask is 0), print it.
            if (mask[str1.charAt(i)] == 0)
                System.out.print(str1.charAt(i));
        }
    }
}

Sample Output:

The given string is: the quick brown fox
The given mask string is: queen

The new string is: 
th ick brow fox

Flowchart:

Flowchart: Java String Exercises - Remove duplicate characters from a given string presents in another given string


For more Practice: Solve these Related Problems:

  • Write a Java program to remove characters from one string that are present in another mask string.
  • Write a Java program to eliminate all characters in a primary string that match any character in a given mask.
  • Write a Java program to filter out duplicate characters from a string based on a separate string of forbidden characters.
  • Write a Java program to remove from a string all characters that appear in a mask string and then display the count of removed characters.

Go to:


PREV : Divide String into Equal Parts.
NEXT : List Items Containing Word Letters.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.