w3resource
Java Programming Exercies

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

Java String: Exercise-41 with Solution

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

Pictorial Presentation:

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

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 public static void main(String[] args) {
  String str1 = "the quick brown fox";
  String str2 = "queen";
  System.out.println("The given string is: " + str1);
  System.out.println("The given mask string is: " + str2);
  char arr[] = new char[str1.length()];
  char[] mask = new char[256];
  for (int i = 0; i < str2.length(); i++)
   mask[str2.charAt(i)]++;
  System.out.println("\nThe new string is: ");
  for (int i = 0; i < str1.length(); i++) {
   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

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to divide a string in n equal parts.
Next: Write a Java program to print list items containing all characters of a given word.

What is the difficulty level of this exercise?