C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Mask String Program - Java Program

Given are two strings, input string and a mask string that remove all the characters of the mask string from the original string.

Example:
INPUT:
ORIGINAL STRING: communication
MASK STRING: mont
OUTPUT: cuicai

A class StringOp is defined as follows to perform above operation.

Some of the members of the class are given below:

Class name: StringOp

Data members/instance variables:
str: to store the original string
msk: to store the mask string
nstr: to store the resultant string

Methods/Member functions:
StringOp(): default constructor to initialize the data members with legal initial values

void accept(): to accept the original string str and the mask string msk in lowercase
void form(): to form the new string nstr after removal of characters present in mask string from the original string.
void display(): to display the original string nstr and the newly formed string nstr

Specify the class StringOp giving details of the constructor, void accept(), void form() and void display(). Define a main() function to create an object and call all the functions accordingly to enable the task.

import java.util.Scanner; class StringOp{ String str; String msk; String nstr; public StringOp(){ str = new String(); msk = new String(); nstr = new String(); } public void accept(){ Scanner in = new Scanner(System.in); System.out.print("ORIGINAL STRING: "); str = in.nextLine().toLowerCase(); System.out.print("MASK STRING: "); msk = in.nextLine().toLowerCase(); } public void form(){ for(int i = 0; i < str.length(); i++){ char ch = str.charAt(i); if(msk.indexOf(ch) == -1) nstr += ch; } } public void display(){ System.out.println("ORIGINAL STRING: " + str); System.out.println("NEWLY FORMED STRING: " + nstr); } public static void main(String[] args){ StringOp obj = new StringOp(); obj.accept(); obj.form(); obj.display(); } }

Output

 
OUTPUT :
ORIGINAL STRING: communication
MASK STRING: mont
ORIGINAL STRING: communication
NEWLY FORMED STRING: cuicai