This is the Java Program to Remove Characters that belong to a Mask String from the Input String
Given a string of characters and a mask string remove all the characters of the mask string from the first string.
Example:
String x = “We belong to Russia”
Mask = “Wbos”
Output = “e elng t Ruia”
Count the frequency of each character in the mask string in an array. Now, iterate through the user string and check each characters frequency in the frequency array. If it is zero, add that character to the output string.
Here is the source code of the Java Program to Remove Characters that belong to a Mask String from the Input String. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Remove Characters that belong
// to a Mask String from the Input String
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveMaskChar {
// Function to remove the mask characters
static String removeMaskCharacters(String str, String str2){
int[] array = new int[256];
int i;
for(i=0; i<str2.length(); i++){
array[str2.charAt(i)]++;
}
String output="";
for(i=0; i<str.length(); i++){
if(array[str.charAt(i)] == 0)
output+=str.charAt(i);
}
return output;
}
// Function to read input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
} catch (IOException e) {
System.out.println("An I/O error occurred");
return;
}
String str2;
System.out.println("Enter the second string");
try {
str2 = br.readLine();
} catch (IOException e) {
System.out.println("An I/O error occurred");
return;
}
String output = removeMaskCharacters(str,str2);
System.out.println("Final String is " + output);
}
}
1. In function removeMaskCharacters(), an array is created to count the frequency of each character in the mask string.
2. The loop for(i=0; i<str2.length(); i++) is used to count the above mentioned frequencies.
3. The loop for(i=0; i<str.length(); i++) is used to iterate through the original string.
4. The condition if(array[str.charAt(i)] == 0) checks if the frequency of the current character in the array is equal to zero.
5. If it is zero, then the element is added to the output string.
Time Complexity: O(n) where n is the length of the string.
Case 1 (Simple Test Case): Enter the string We belong to Russia Enter the second string Wbos Final String is e elng t Ruia Case 2 (Simple Test Case - another example): Enter the string xyz Enter the second string xyz Final String is
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Computer Science Internship
- Practice BCA MCQs
- Check Programming Books
- Check Java Books
- Practice Information Technology MCQs